User Input In Date Time Format Python
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!
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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module