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
CodePudding user response:
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