How to Convert DateTime to UNIX Timestamp in Python

By FoxLearn 12/3/2024 3:35:56 PM   10
The Unix timestamp is a single signed integer representing the number of seconds elapsed since January 1, 1970, making it useful for computers to store and manage date systems. It can be converted into a human-readable format.

To convert Python DateTime to a Unix timestamp, the datetime and time modules are used.

# importing datetime module
import datetime
import time
 
# assigned regular string date
dt = datetime.datetime(2024, 8, 25, 21, 20)

# print regular python date & time
print("date_time =>", dt)
 
# displaying unix timestamp after conversion
print("unix_timestamp => ", (time.mktime(dt.timetuple())))

In Python, the datetime module provides classes for manipulating dates and times. To convert a datetime object to a Unix timestamp (the number of seconds since January 1, 1970), you can use the timestamp() method:

For example: Get the Current Unix Timestamp

from datetime import datetime

# Create a datetime object
dt = datetime(2024, 12, 3, 10, 27, 17)

# Convert to Unix timestamp
timestamp = dt.timestamp()
print(timestamp)

For example: DateTime to Unix timestamp in UTC Timezone

The calendar module offers useful calendar-related functions. The utcnow() function from the datetime module provides the current time in the UTC timezone. The timegm() function from the time module converts a timetuple() (returned by datetime) into a Unix timestamp. Use these together to retrieve and display the current UTC timestamp.

import calendar
import datetime
 
dt = datetime.datetime.utcnow()
utc_time = calendar.timegm(dt.utctimetuple())
print(utc_time)