Converting Unix timestamp string to readable date
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:
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:
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:
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:
Type errors: Wrong type at the wrong time
Allergic to TypeError
? Avoid feeding time.strftime
strings when it craves numerals:
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
:
Got a date with pandas DataFrame?
Data scientists can swing Unix timestamps in a pandas DataFrame with ease:
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:
Was this article helpful?