Explain Codes LogoExplain Codes Logo

Convert string date to timestamp in Python

python
date-conversion
timestamp
datetime
Nikita BarsukovbyNikita BarsukovΒ·Aug 26, 2024
⚑TLDR

Here's a quick solution to convert a date string to a Unix timestamp. We'll use datetime.strptime() for parsing the string and datetime.timestamp() to get the Unix timestamp:

from datetime import datetime timestamp = datetime.strptime("2023-01-01 12:00:00", "%Y-%m-%d %H:%M:%S").timestamp() print(timestamp) # New Year's Party... in Unix time πŸŽ‰

πŸ”‘ Key point: Ensure your date format corresponds with the strptime() format.

Deep dive into conversion

Covering different date formats

Using strptime(), you can parse a multitude of date formats. For a date string like "31/01/2023" (DD/MM/YYYY), here's how:

from datetime import datetime date_string = "31/01/2023" # Euro-style dates, because we're sophisticated 🎩 date_format = "%d/%m/%Y" datetime_obj = datetime.strptime(date_string, date_format) timestamp = datetime_obj.timestamp()

Ensure to match your date_format with your date_string.

Eliminating time-zone headaches

For a UTC timestamp, avoid time-zone problems with this:

from calendar import timegm utc_timestamp = timegm(datetime_obj.utctimetuple()) # Bye, timezone issues πŸ‘‹

And, if your string date includes time zone info:

from datetime import datetime, timezone datetime_obj = datetime.strptime(date_string, date_format).replace(tzinfo=timezone.utc) timestamp = datetime_obj.timestamp()

This explicitly sets the timezone to UTC.

Speeding up with third-party libraries

While datetime is versatile, ciso8601 is a faster choice for parsing ISO 8601 date strings:

import ciso8601 timestamp = ciso8601.parse_datetime(date_string).timestamp() # ciso8601: You'll almost see it blushing at its own speed πŸŽοΈπŸ’¨

Note that ciso8601 is tailored for the ISO 8601 format and thus, may not fit other formats.

Building robust conversion practices

Safeguarding with error handling

Shield your date parsing within a try-except block for error resiliency:

try: timestamp = datetime.strptime(date_string, date_format).timestamp() except ValueError: print("Incorrect format or date") # Oops! Something went wrong? Blame the error, not me :)

Using strftime("%s") with caution

While strftime("%s") yields timestamps, it's platform-dependent. Use .timestamp() for greater compatibility:

timestamp = int(datetime_obj.strftime("%s")) # Timestamps, now served as integers!

Pandas for date-strings in data science

If you're a data science aficionado, pandas.to_datetime() comes real handy:

import pandas as pd timestamp = pd.to_datetime(date_string).timestamp() # Pandas, not just cute creatures! 🐼

Beware the leap seconds

Timestamps have discontinuities due to leap seconds. Make manual adjustments as datetime libraries don't account for leap seconds.

Importing libraries and formatting accurately

Ensure valid import statements and accurate format specifiers for strptime to enjoy a smooth conversion.