Explain Codes LogoExplain Codes Logo

Converting Unix timestamp string to readable date

python
datetime
timestamp
pandas
Anton ShumikhinbyAnton Shumikhin·Sep 6, 2024
TLDR

To quickly change a Unix timestamp to a readable date, use Python's datetime module. Convert the timestamp into an integer and call datetime.fromtimestamp(). Example:

from datetime import datetime readable_date = datetime.fromtimestamp(int("1609459200")).strftime('%Y-%m-%d %H:%M:%S') print(readable_date) # Outputs: 2021-01-01 00:00:00

Easy as pie, strftime('%Y-%m-%d %H:%M:%S') formats your date to YYYY-MM-DD HH:MM:SS format.

Complexity? Bring it on!

When Unix timestamp came in milliseconds

Wondering how to handle Unix timestamps in milliseconds? Simply divide by 1000:

timestamp_ms = "1609459200000" # Unix timestamp in milliseconds # Bob from Accounting's strategy of "divide and conquer" readable_date = datetime.fromtimestamp(int(timestamp_ms) / 1000).strftime('%Y-%m-%d %H:%M:%S')

The Silent Scream of ValueError

Beware of the ValueError: "timestamp out of range for platform localtime()/gmtime()". This blinks when your timestamp strays from the Epoch and 2038 window. Adjust input to keep the temporal peace.

Stretching Unix timestamps

Time zones: UTC or local?

Time zones messing with your timestamp? The tzlocal module flexibly switches between local and UTC times:

from datetime import datetime from tzlocal import get_localzone local_timezone = get_localzone() local_time = datetime.fromtimestamp(int("1609459200"), local_timezone)

If the UTC agenda suits you better, opt for datetime.utcfromtimestamp().

Using time for backward compatibility

Running older versions of Python? The time module is your walk down the memory lane:

import time local_time = time.ctime(int("1609459200")) # Oldies but goodies utc_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int("1609459200")))

Type errors: Wrong type at the wrong time

Allergic to TypeError? Avoid feeding time.strftime strings when it craves numerals:

timestamp_str = "1609459200" # Recovering from a Twix, er, type mix time.ctime(int(timestamp_str))

Kicking it up a notch

Milliseconds or seconds?

Does your Unix timestamp resemble a phone number? It's possibly in milliseconds. Remember, just divide by 1000.

Customize date format

Want to scribble your date your way? Whip up a custom format with time.strftime:

import time # Did you know "May the fourth be with you" uses this format? No kidding! formatted_time = time.strftime('%B %d %Y', time.localtime(int("1609459200")))

Got a date with pandas DataFrame?

Data scientists can swing Unix timestamps in a pandas DataFrame with ease:

import pandas as pd # pandas on a date with Unix Timestamp, how charming! df['date'] = pd.to_datetime(df['timestamp'], unit='s')

The time alternative

In the land of the time module, time.ctime() offers an escape from format strings, helping you strftime without working up a sweat:

import time readable_date = time.ctime(int("1609459200")) # lazy coder's way of dealing with time