Ad

User Input In Date Time Format Python

- 1 answer

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!

Ad

Answer

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
Ad
source: stackoverflow.com
Ad