Python program to convert unix timestamp string to readable date
In this article, we are going to see the conversion of the Unix timestamp string to a readable date. This can be done with the help of fromtimestamp() and strftime() functions.
Functions Used
fromtimestamp(): The fromtimestamp() function is used to return the date and time corresponding to a specified timestamp.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method.
Syntax: @classmethod fromtimestamp(timestamp)
Parameters: This function accepts a parameter which is illustrated below:
- timestamp: This is the specified timestamp for which the date is going to be returned.
Return values: This function returns the date and time corresponding to a specified timestamp.
strftime(): The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string representation.
Syntax: strftime(format)
Parameter: This function accepts a single parameter which is illustrated below:
- format: This is the specified date and time object.
Return Values: It returns the string representation of the date or time object.
Let’s see the example to convert the specified Unix timestamp string to a readable date
Example 1: Convert the specified Unix timestamp string.
Python
# Python program to illustrate the# conversion of unix timestamp string# to its readable date# Importing datetime moduleimport datetime# Calling the fromtimestamp() function to# extract datetime from the given timestamp# Calling the strftime() function to convert# the extracted datetime into its string formatprint(datetime.datetime.fromtimestamp(int("1294113662")) .strftime('%Y-%m-%d %H:%M:%S')) |
Output:
2011-01-04 04:01:02
Example 2: Convert the specified Unix timestamp string.
Python
# Python program to illustrate the# conversion of unix timestamp string# to its readable date# Importing datetime moduleimport datetime# Calling the fromtimestamp() function to# extract datetime from the given timestamptimestamp = datetime.datetime.fromtimestamp(1200001234)# Calling the strftime() function to convert# the extracted datetime into its string formatprint(timestamp.strftime('%Y-%m-%d %H:%M:%S')) |
Output:
2008-01-10 21:40:34


