2023-06-22 18:56:11 +00:00
|
|
|
from ctparse import ctparse #Used for parsing time (parsetime), https://github.com/comtravo/ctparse
|
|
|
|
import parsedatetime #Used for parsing time (parsetime2), https://github.com/bear/parsedatetime
|
|
|
|
|
2023-06-22 17:14:13 +00:00
|
|
|
from datetime import datetime
|
2023-06-22 18:56:11 +00:00
|
|
|
import time
|
2023-06-22 17:14:13 +00:00
|
|
|
|
|
|
|
def parsetime(phrase):
|
2023-06-22 18:56:11 +00:00
|
|
|
"""
|
|
|
|
Takes in natrual language time phrase, outputs datetime object
|
|
|
|
"""
|
|
|
|
|
2023-06-22 17:14:13 +00:00
|
|
|
ts = datetime.now()
|
2023-06-22 18:56:11 +00:00
|
|
|
p = ctparse(phrase, ts=ts)
|
|
|
|
if p is not None:
|
|
|
|
return p.resolution.dt
|
|
|
|
return p
|
|
|
|
|
|
|
|
# return ctparse(phrase, ts=ts)
|
|
|
|
|
|
|
|
|
|
|
|
def parsetime2(phrase):
|
|
|
|
"""
|
|
|
|
Takes in natrual language time phrase, outputs datetime object
|
|
|
|
Handles seconds better
|
|
|
|
Doesnt handle 'in the afternoon'
|
|
|
|
Does handle 'this afternoon'
|
|
|
|
"""
|
2023-06-22 17:14:13 +00:00
|
|
|
|
2023-06-22 18:56:11 +00:00
|
|
|
time_struct, parse_status = parsedatetime.Calendar().parse(phrase)
|
|
|
|
return datetime(*time_struct[:6])
|
2023-06-22 17:14:13 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2023-06-22 18:56:11 +00:00
|
|
|
t = parsetime('May 5th 2:30 in the afternoon')
|
|
|
|
print(t)
|
|
|
|
|
|
|
|
# t2 = parsetime('15 seconds')
|
|
|
|
# # print(t2)
|
|
|
|
# # print(t2)
|
|
|
|
# if t2 is not None:
|
|
|
|
# print(t2.resolution)
|
|
|
|
|
|
|
|
|
|
|
|
t2 = parsetime2('now')
|
|
|
|
print(time.mktime(t2.timetuple()))
|
|
|
|
|
|
|
|
t3 = parsetime2('in 5 minutes 30 seconds')
|
|
|
|
print(time.mktime(t3.timetuple()))
|
|
|
|
|
|
|
|
print(time.strftime("%H:%M:%S", t3.timetuple()))
|
|
|
|
# for x in t:
|
|
|
|
# print(x)
|