Skip to content

How to get the UTC Timestamp in Python

All dates in your server applications should be stored in the UTC timezone.

This is because you always want to store time without the offset of the timezone you may be working in.

Clients of your application may be in many different timezones around the world. However, storing all data in the UTC or GMT (same thing) timezone, is ideal as it gives your application the ability to present times and dates back in the same methodology.

Option 1

We always import the datetime module, but this option allows us to make sure that we are providing times from the timezone.utc module.

from datetime import datetime, timezone"%Y-%m-%d %H:%M:%S")
Code language: Python (python)

Option 2

You can also exclude the timezone module and do it as follows:

from datetime import datetime datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
Code language: Python (python)


I personally prefer the first option (Option 1), as it is more timezone aware. Eventhough both options will work just fine, the former allows the ability to think more timezone centric.

See also  How to Select From MySQL in Python
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x