How to get the UTC Timestamp in Python

0 min read 161 words

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
datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")

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")

Rationale

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.

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags