I need to get date and time from the user and convert it to epoch. I'm pretty new to Python, so don't judge the question harshly =) I've done my research and if I understand correctly, the only way to get the input from a user in Python 3.x is through input() which retrieves either a string or an int. My current plan is to use input(), parse the string with dateutil parser, and then do something like:
import time
time_now = time.strptime('2019-08-30 18:37:06', '%Y-%m-%d %H:%M:%S')
time_epoch = time.mktime(time_now)
Is there a simpler way to achieve this? Maybe, there is a version of input() or a function to achieve this and I'm reinventing the wheel? Thanks in advance!
If you're using Python 3.3 or newer, you can simply call the timestamp
method of the datetime
object to get the epoch timestamp. No need to import time
.
>>> from dateutil.parser import parse
>>> value = parse('2019-08-31 12:20')
>>> value.timestamp()
1567246800.0
Note that you may wish to set up handling of invalid user input that can't be parsed. You can do this by catching any ValueError
exceptions:
try:
value = parse(input('Date: '))
except ValueError:
# user input couldn't be parsed -- handle this however you need to
import calendar
MM,DD,YYYY = map(int,input().split())
day = calendar.weekday(YYYY,MM,DD)
daynumber =[
'MONDAY','TUESDAY', 'WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY'
]
print(daynumber[day])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.