'Convert given UTC timestamp string to unix timestamp
I'm struggling with this small snippet:
import time
from datetime import datetime
start = "2022-05-14T10:00:00"
start_date = datetime.fromisoformat(start)
start_unix = time.mktime(start_date.timetuple())
print(start_unix)
#1652515200.0
The start date regardless how it looks is in UTC while I'm in a different timezone. Python threats this datetime string/object as it would be in the same timezone I am. How to convert the datetime string object the easiest way to get a proper UNIX timestamp? The expected result should be:
1652522400.0
Solution 1:[1]
Set the tzinfo of the resulting datetime object to UTC (replace
method), then call .timestamp()
method of the aware datetime object. Ex:
from datetime import datetime, timezone
start = "2022-05-14T10:00:00"
start_unix = datetime.fromisoformat(start).replace(tzinfo=timezone.utc).timestamp()
print(start_unix)
# 1652522400.0
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 | FObersteiner |