Explain Codes LogoExplain Codes Logo

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

python
datetime
timestamp
unix-time
Nikita BarsukovbyNikita Barsukov·Nov 13, 2024
TLDR

Convert a datetime to Unix time milliseconds with timestamp().

from datetime import datetime # This line of code brings joy to Pythonistas milliseconds = int(datetime.now().timestamp() * 1000)

This speedy solution fetches the current time as Unix milliseconds. To convert a custom datetime object or wrangle with different time zones, keep scrolling!

Broken down: Conversion process

The process of converting a datetime object to Unix time milliseconds involves interacting with the Unix Epoch, a point in time established on January 1, 1970, that forms the basis of Unix time.

Pre-Python 3.3: Old-school conversions

For Python versions prior to 3.3, the to-epoch conversion requires more elaborate steps:

import time from datetime import datetime # Oldie but a goodie, like Grandma's cookie recipe dt = datetime.now() epoch = datetime.utcfromtimestamp(0) # The Big Bang of Unix time delta = dt - epoch # Time travel to 1970! milliseconds = int(delta.total_seconds() * 1000) # Magic happens here

Timezone games: Aware conversions

For timezone-aware datetime objects, the timestamp() function is your best friend:

from datetime import datetime, timezone # Spacetime-aware datetime object, in UTC we trust! dt = datetime.now(timezone.utc) milliseconds = int(dt.timestamp() * 1000) # Easy peasy lemon squeezy

Micro-measures: Extra precision

If your application demands micrometric precision, include the microseconds in your computations:

from datetime import datetime dt = datetime.now() # Milliseconds on steroids, we don't miss even a microsecond milliseconds = int(dt.timestamp() * 1000) + int(dt.microsecond / 1000)

Context matters: Use cases

Timestamp conversions play a crucial role in scenarios such as logging, syncing systems, or whenever high-resolution timestamps are required. Always be aware of entity details like time zones, handling leap seconds, or adjustments due to Daylight Saving Time.

UNIX warriors: Converting seconds

In the heat of the coding moment, you may face a Unix timestamp in seconds requiring transformation to a datetime object or milliseconds:

seconds_since_epoch = 1615423407 milliseconds_since_epoch = seconds_since_epoch * 1000 # Becoming richer, millisecond-wise # To convert back to a datetime object dt = datetime.utcfromtimestamp(seconds_since_epoch) # Back to the future!

Legacy tales: String formatting

Dusty corners of Python, legacy code might work with a more archaic method:

import datetime # Vintage conversion, only hipsters use this milliseconds = int(datetime.datetime.now().strftime("%s")) * 1000

This method is not recommended, as it's platform-dependent and lacks forward compatibility.

Library Luxuries: datetime Alternatives

Despite the power and versatility of the datetime module, a few third-party libraries smooth out some of its wrinkles. Align your code to these libraries—Arrow, dateutil, and Delorean—to enjoy the luxury of easy datetime manipulations.

Taking Delorean for a spin:

from delorean import Delorean d = Delorean() milliseconds = d.epoch * 1000 # Write code Marty, not dates!

Consult the relevant docs before using these libraries.