'how do you convert user input datetime to epoch time in python
I need to convert user input datetime to epoch time. This what what I have:
from datetime import datetime
from_date = str(input('Enter date(yyyy-mm-dd hh:mm): '))
to_date = str(input('Enter date(yyyy-mm-dd hh:mm): '))
print(from_date)
2022-03-03 06:00:00
print(to_date)
2022-03-03 06:00:00
epoch = datetime.datetime(from_date).strftime('%s')
print(epoch)
Solution 1:[1]
Check date format codes and convert it to a datetime object, then simply use .timestamp().
from datetime import datetime
from_date = "2022-03-03 06:00:00"
epoch = datetime.strptime(from_date, "%Y-%m-%d %H:%M:%S").timestamp()
Solution 2:[2]
First, convert your input to a datetime using datetime.strptime.
Then use dt.timestamp() to convert to EPOCH:
from datetime import datetime
from_date = str(input('Enter date(yyyy-mm-dd hh:mm): '))
dt = datetime.strptime(from_date, '%Y-%m-%d %H:%M:%S')
epoch = dt.timestamp()
print(epoch)
# 1646287200.0
Try it online!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mnikley |
| Solution 2 | 0stone0 |
