How to Use the fromtimestamp() Function in Python

The fromtimestamp() is a built-in Python function from the date class inside the datetime module that returns the date corresponding to a specified timestamp. To get the date from the timestamp in Python, use the datetime.date() function along with the fromtimestamp() function.

What is a timestamp in Python

A timestamp in Python is a long number consisting of the value equal to the date and time. We can get the date and time from a timestamp using the fromtimestamp() function. 

Date Format: year – month – date, represented as (“yy – mm – dd”).

Time Format: Hour: Minute: Seconds.

Python program of fromtimestamp() function

import time
import datetime

current_time = time.time()
print("The current time is : ", current_time)
date_time_format = datetime.datetime.fromtimestamp(current_time)
print("The data time format is : ", date_time_format)

Output

The current time is : 1651059185.7796118
The data time format is : 2022-04-27 17:03:05.779612

In this program, we imported two modules named time and datetime. The time module is used for getting the current time. We can get the time using the time.time() function. We used the fromtimestamp() function to get the date and time in the date-time format.

The fromtimestamp() function gets the current time as a timestamp and gets the date and time from the timestamp. The current date and the time are printed if we execute this program.

We can also get the date and time for the timestamp. Let’s see the example.

import datetime

date_time_format = datetime.datetime.fromtimestamp(1651052961)
print("The data time format is : ", date_time_format)

Output

The data time format is : 2022-04-27 15:19:21

Program for using the fromtimestamp() function to get the date alone in Python

import time
import datetime

current_time = time.time()
print("The current time is : ", current_time)
date_time_format = datetime.date.fromtimestamp(current_time)
print("The data is : ", date_time_format)

Output

The current time is : 1651059647.982643
The data is : 2022-04-27

In this program, we are extracting the date alone from the current time. This fromtimestamp function gets the data whichever is required from the timestamp.

If we use datetime.fromtimestamp() function then the date and time are extracted from the timestamp.

If we use the date.fromtimestamp() function then the date alone is extracted from the timestamp.

We can also extract the date from the given timestamp.

import datetime

date_time_format = datetime.date.fromtimestamp(1651052961)
print("The date is : ", date_time_format)

Output

The date is : 2022-04-27

Conclusion

The fromtimestamp() of the date class is used to compute the date corresponding to a given timestamp and returns it.

That’s it for this tutorial.

Related posts

How to Measure elapsed time between Two Points in Python

Leave a Comment