How to Convert a Date String to Unix Timestamp in Python
A Unix timestamp represents the number of seconds elapsed since the Unix Epoch (January 1, 1970, 00:00:00 UTC). Converting date strings to timestamps is essential for APIs, databases, and time-based calculations.
Converting Local Time Strings
When the date string represents local time, use datetime.timestamp():
from datetime import datetime
date_string = "2023-12-31 23:59:59"
format_string = "%Y-%m-%d %H:%M:%S"
dt = datetime.strptime(date_string, format_string)
timestamp = dt.timestamp()
print(timestamp) # e.g., 1704067199.0
This method interprets the string as local system time and converts accordingly.
Converting UTC Time Strings
For UTC strings, use calendar.timegm() to avoid timezone confusion:
import calendar
from datetime import datetime
date_string = "2023-01-01 12:00:00"
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
# Treat as UTC explicitly
timestamp = calendar.timegm(dt.utctimetuple())
print(timestamp) # 1672574400
Alternatively, create a timezone-aware datetime:
from datetime import datetime, timezone
date_string = "2023-01-01 12:00:00"
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
dt_utc = dt.replace(tzinfo=timezone.utc)
timestamp = dt_utc.timestamp()
print(timestamp) # 1672574400.0
A naive datetime (without timezone info) will be treated as local time by timestamp(). This causes different results on machines in different timezones.
Handling ISO 8601 Format
Python 3.7+ can parse ISO format strings directly:
from datetime import datetime, timezone
# With timezone offset
iso_string = "2023-06-15T14:30:00+00:00"
dt = datetime.fromisoformat(iso_string)
timestamp = dt.timestamp()
print(timestamp) # 1686839400.0
# UTC indicator (Python 3.11+)
iso_utc = "2023-06-15T14:30:00Z"
# For Python < 3.11, replace Z with +00:00
dt = datetime.fromisoformat(iso_utc.replace("Z", "+00:00"))
Flexible Parsing with dateutil
For varied or human-readable date formats:
pip install python-dateutil
from dateutil import parser
# Handles many formats automatically
dates = [
"Jan 1st, 2026 5pm",
"December 25, 2026",
"2026/06/15 14:30",
"15-06-2026",
]
for date_string in dates:
dt = parser.parse(date_string)
print(f"{date_string} -> {dt.timestamp()}")
Output:
Jan 1st, 2026 5pm -> 1767286800.0
December 25, 2026 -> 1798156800.0
2026/06/15 14:30 -> 1781533800.0
15-06-2026 -> 1781481600.0
The dateutil.parser is forgiving with formats but may guess incorrectly for ambiguous dates like "01/02/2023". Use dayfirst=True or yearfirst=True parameters to control interpretation.
Integer vs Float Timestamps
Some systems use integer timestamps (seconds) while others use milliseconds:
from datetime import datetime
date_string = "2026-06-15 14:30:00"
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
# Standard Unix timestamp (float seconds)
timestamp_float = dt.timestamp()
# Integer seconds
timestamp_int = int(dt.timestamp())
# Milliseconds (common in JavaScript/APIs)
timestamp_ms = int(dt.timestamp() * 1000)
print(f"Seconds (float): {timestamp_float}")
print(f"Seconds (int): {timestamp_int}")
print(f"Milliseconds: {timestamp_ms}")
Output:
Seconds (float): 1781533800.0
Seconds (int): 1781533800
Milliseconds: 1781533800000
Handling Multiple Timezones
Convert strings with timezone information properly:
from datetime import datetime, timezone, timedelta
# String with known timezone offset
date_string = "2026-06-15 14:30:00"
offset_hours = -5 # EST
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
tz = timezone(timedelta(hours=offset_hours))
dt_aware = dt.replace(tzinfo=tz)
timestamp = dt_aware.timestamp()
print(f"Timestamp: {timestamp}")
Output:
Timestamp: 1781551800.0
Using zoneinfo (Python 3.9+):
from datetime import datetime
from zoneinfo import ZoneInfo
date_string = "2023-06-15 14:30:00"
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
# Assign specific timezone
dt_ny = dt.replace(tzinfo=ZoneInfo("America/New_York"))
dt_tokyo = dt.replace(tzinfo=ZoneInfo("Asia/Tokyo"))
print(f"Same time, NYC: {dt_ny.timestamp()}")
print(f"Same time, Tokyo: {dt_tokyo.timestamp()}")
Output:
Same time, NYC: 1686853800.0
Same time, Tokyo: 1686807000.0
Complete Conversion Function
A robust function handling various scenarios:
from datetime import datetime, timezone
import calendar
from typing import Optional
def to_timestamp(
date_string: str,
format_string: str = "%Y-%m-%d %H:%M:%S",
assume_utc: bool = False,
as_milliseconds: bool = False
) -> Optional[float]:
"""
Convert date string to Unix timestamp.
Args:
date_string: The date string to convert
format_string: strptime format pattern
assume_utc: If True, treat naive datetime as UTC
as_milliseconds: If True, return milliseconds instead of seconds
Returns:
Unix timestamp as float, or None if parsing fails
"""
try:
dt = datetime.strptime(date_string, format_string)
if assume_utc:
timestamp = calendar.timegm(dt.utctimetuple())
else:
timestamp = dt.timestamp()
if as_milliseconds:
return timestamp * 1000
return timestamp
except ValueError as e:
print(f"Parse error: {e}")
return None
# Usage examples
print(to_timestamp("2026-06-15 14:30:00"))
print(to_timestamp("2026-06-15 14:30:00", assume_utc=True))
print(to_timestamp("2026-06-15 14:30:00", as_milliseconds=True))
Output:
1781533800.0
1781533800
1781533800000.0
Common Format Codes
| Code | Meaning | Example |
|---|---|---|
%Y | 4-digit year | 2023 |
%m | Month (zero-padded) | 06 |
%d | Day (zero-padded) | 15 |
%H | Hour (24-hour) | 14 |
%M | Minute | 30 |
%S | Second | 00 |
%z | UTC offset | +0000 |
%Z | Timezone name | UTC |
Method Comparison
| Method | Timezone Handling | Best For |
|---|---|---|
dt.timestamp() | Assumes local time | Local time strings |
calendar.timegm() | Assumes UTC | UTC time strings |
dt.replace(tzinfo=...) | Explicit timezone | Known timezone data |
datetime.fromisoformat() | Parses from string | ISO 8601 format |
Always be explicit about timezones in production code. A naive datetime created on a server in UTC will produce different timestamps than the same code run on a laptop in a different timezone.
For consistent results across different environments, prefer timezone-aware datetime objects and explicitly specify whether input strings represent UTC or local time.