Convert Date String to Timestamp in Python
Last Updated :
23 Aug, 2025
To convert a date string to a timestamp, we first parse it into a format Python understands, then convert it to the number of seconds since January 1, 1970 (the Unix epoch). For example, "20/01/2020" becomes 1579478400.0.
Let’s explore simple and efficient ways to do this.
Using datetime.timestamp()
datetime.timestamp() converts a datetime object to a Unix timestamp in seconds and returns a float. It assumes local time if no timezone is set and is a simple, modern choice for quick conversions.
Python
from datetime import datetime
s = "20/01/2020"
dt = datetime.strptime(s, "%d/%m/%Y")
res = dt.timestamp()
print(res)
Explanation: s holds the date string, which is parsed into a datetime object dt using the format %d/%m/%Y. dt.timestamp() then converts it to a Unix timestamp, which is stored in res.
Using calendar.timegm()
calendar.timegm() method takes a UTC time tuple and returns an integer timestamp, making it ideal when you need timezone-independent, UTC-based results.
Python
from datetime import datetime
import calendar
s = "20/01/2020"
dt = datetime.strptime(s, "%d/%m/%Y")
res = calendar.timegm(dt.utctimetuple())
print(res)
Explanation: s holds the date string, parsed into a datetime object dt. calendar.timegm(dt.utctimetuple()) converts it to a UTC-based Unix timestamp, stored in res.
Using time.mktime()
time.mktime() converts a local time tuple to a timestamp and returns a float; it reflects your system’s timezone, so it’s best for local time operations.
Python
from datetime import datetime
import time
s = "20/01/2020"
dt = datetime.strptime(s, "%d/%m/%Y")
res = time.mktime(dt.timetuple())
print(res)
Explanation: s holds the date string, parsed into dt. time.mktime(dt.timetuple()) converts it to a local Unix timestamp, stored in res.
Using pandas.to_datetime()
pandas.to_datetime().timestamp() parses a date string into a datetime object and returns a float timestamp. It is perfect for handling large datasets or performing time-based data analysis using pandas.
Python
import pandas as pd
s = "20/01/2020"
res = pd.to_datetime(s, format="%d/%m/%Y").timestamp()
print(res)
Explanation: s holds the date string, parsed by pd.to_datetime() and converted to a Unix timestamp using .timestamp(), stored in res.
Related articles
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice