Python fromtimestamp: Get the date from a timestamp – Datetime.fromtimestamp()
Python fromtimestamp: In this article, we will learn how to compute the data corresponding to a given timestamp.
In a database, it is common to store the date and time as a timestamp.
The Unix time also called Unix Timestamp is a measure of time based on the number of seconds elapsed since January 1, 1970 00:00:00 UTC, excluding leap seconds. It is the POSIX representation of time. The origin of the POSIX time has been chosen as January 1st 1970 00:00:00, this date corresponds to the 0 time of Posix, it is called the Posix epoch (and also Unix epoch).
from datetime import datetime import time current_date = datetime.fromtimestamp(time.time()); print("current_date =", current_date) print("type(current_date) =", type(current_date))
When you run the program below, you will get the current date:
current_date = 2021-08-22 10:29:12.366731 type(current_date) = <class 'datetime.datetime'>
In our example, we imported the datetime class from the datetime module. This class has a method called fromtimestamp() which returns the local date and time. This object is stored in an object called current_date.
If you want to create a string representing only the date from a timestamp, you can use the strftime() method:
from datetime import datetime import time current_date = datetime.fromtimestamp(time.time()).strftime('%m/%d/%Y') print("current_date =", current_date) print("type(current_date) =", type(current_date))
You will get the following result:
current_date = 08/22/2021 type(current_date) = <class 'str'>
The function allows to return a string from a datetime object.
Python fromtimestamp – TimeZone
To get a date taking into account a specific time zone, the function fromtimestamp() can take a tz parameter. Here is an example:
from datetime import datetime, timezone ts = 1571234567.0 x = datetime.fromtimestamp(ts, tz=timezone.utc) print(x) >>> 2019-10-16 14:02:47+00:00
In this tutorial, we have seen how to retrieve a date and time from a timestamp using the Datetime.fromtimestamp() method.
Some people use utcnow() and utcfromtimestamp() instead of now() and fromtimestamp(). Personally, I would advise you not to use these two functions because it is not the right abstraction (it gives a representation of a concrete point in time as an abstract date).
I hope this tutorial has given you a better understanding of how to convert a timestamp into an understandable date. If you have any questions about how to use it, don’t hesitate to tell me in comments.
See you soon for new tutorials !