October 13, 2024

Python epoch to datetime

In Python, you can convert an epoch timestamp (number of seconds since January 1, 1970) to a human-readable datetime object using the datetime module. The epoch timestamp is commonly used in Unix-based systems and various programming scenarios.

1. Converting Epoch to Datetime

You can use the datetime module to convert an epoch timestamp to a datetime object:

from datetime import datetime

# Example epoch timestamp
epoch_timestamp = 1693708800

# Convert epoch to datetime
dt = datetime.fromtimestamp(epoch_timestamp)
print(dt)  # Output: 2024-09-01 00:00:00
    

2. Handling Timezones

If you need to handle timezones, you can use the pytz library in combination with datetime:

from datetime import datetime
    import pytz

# Example epoch timestamp
epoch_timestamp = 1693708800

# Convert epoch to datetime with timezone
utc_zone = pytz.utc
dt = datetime.fromtimestamp(epoch_timestamp, tz=utc_zone)
print(dt)  # Output: 2024-09-01 00:00:00+00:00
    

3. Converting Datetime to Epoch

To convert a datetime object back to an epoch timestamp, you can use the timestamp() method:

from datetime import datetime

# Example datetime
dt = datetime(2024, 9, 1)

# Convert datetime to epoch
epoch_timestamp = dt.timestamp()
print(epoch_timestamp)  # Output: 1693708800.0
    

4. Conclusion

Converting between epoch timestamps and datetime objects in Python is straightforward using the datetime module. This conversion is useful for handling timestamps, performing date arithmetic, and integrating with systems that use epoch time.