/  Technology   /  Converting unix timestamp string to readable date in Python

Converting unix timestamp string to readable date in Python

 

In this article, let’s learn how to convert a unix timestamp string to a readable date. This can be done using two functions, namely, fromtimestamp() and strftime(), which are available in the datetime module.

 

fromtimestamp():

This function is a class method that returns the date and time corresponding to a given timestamp.

Syntax: 

@classmethod fromtimestamp(timestamp)

This function takes in ‘timestamp’ as a parameter, to which the date is going to be returned.

 

strftime(): 

This function converts date and time objects to their respective string representation. It takes one or more inputs of formatted code and returns the string representation.

Syntax:

strftime(format)

This function accepts a single parameter, the format code which is the specified date and time object.

 

The most frequently used format codes are:

  • %d which represents the day of the month. 

Example: 01, 02, …, 31

  • %B which represents the complete month’s name.

Example: January, February etc.

  • %Y which represents the year that is four digits long. 

Example: 2018, 2019 etc.

  • %I which represents 12-hour clock as a zero-padded decimal 

Example: 01, 02, …, 12

  • %p which represents whether it’s AM or PM.
  • %M which represents minutes as a zero-padded decimal.

Example: 01, 02, …, 59

 

This function returns the string representation of the date or time object.

Example:

import datetime

print(datetime.datetime.fromtimestamp(int("1232512334"))
   .strftime(%Y-%m-%d %H:%M:%S'))

Output:

 

Leave a comment