Explain Codes LogoExplain Codes Logo

How to get UTC time in Python?

python
datetime
timezone
timestamp
Nikita BarsukovbyNikita Barsukov·Feb 18, 2025
⚡TLDR

Straight to the code! Obtain UTC time in Python instantly with:

from datetime import datetime print(datetime.utcnow()) # "What's the time?" "UTC time, my friend. Always."

This is how you secure a timezone-naive UTC timestamp in one simple line.

Get UTC time with timezone awareness

For applications dealing with multiple time zones, it's important to use timezone-aware datetime. Let's get hands-on with Python 3:

from datetime import datetime, timezone utc_time = datetime.now(timezone.utc) print(utc_time) # UTC time with an awareness of its timezone

This imbeds timezone awareness into the datetime, making it a smooth operator across different timezones.

Calculate time intervals with precision

To calculate the time elapsed between two events, you'll need to:

from datetime import datetime, timezone start = datetime.now(timezone.utc) # Time-consuming operation here end = datetime.now(timezone.utc) time_spent = end - start print(time_spent.total_seconds()) # Elapsed time in seconds, with microsecond precision

By subtracting start from end time, we get a timedelta object. The total_seconds() method converts this interval into seconds - easier for human brains to interpret.

Getting to grips with Unix time format

Dealing with time in Unix epoch format? Here's how you translate Python's datetime to Unix time:

from datetime import datetime, timezone unix_time = datetime.now(timezone.utc).timestamp() # Timestamp? Time's stamp of approval. print(unix_time)

And to convert to milliseconds, a matter of simple multiplication:

milliseconds_since_epoch = unix_time * 1000 # "Seconds are too slow. Let's milliseconds!"

Timezone-aware calculations - the nuts and bolts

Performing timezone-aware operations is nothing to sneeze at. Fielding calculated timedelta objects and accounting for time zone disparities spells the success of distributed systems.

Pytz: your timezone toolkit

For coders who predate Python 3.2, the pytz library is your best friend:

import pytz from datetime import datetime utc_time_with_pytz = datetime.now(pytz.utc) # "It's always UTC o'clock somewhere." print(utc_time_with_pytz)

This is your go-to until datetime.now(timezone.utc) was introduced with Python's 3.2 version.

Consistent across platforms

Consistency is key in all Python applications. UTC time using datetime.now(timezone.utc)? That's consistent across platforms. Cheers to cross-platform compatibility!

Few final tips for robust results

  • Make a habit to replace datetime.utcnow() with datetime.now(timezone.utc) when you need timezone-aware datetime.
  • For all time interval calculations, stick to timedelta objects. They're your shield against time-related mistakes.
  • When it comes to epoch time, use true division (/) and not floor division (//). This avoids truncation errors during your milliseconds conversion project.