0

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
1
  • @FObersteiner this is exactly what I needed, please post it as a reply for me to upvote it. Thanks a lot! Commented May 14, 2022 at 8:57

1 Answer 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.