API · Python

Python datetime.utcfromtimestamp() Class

The datetime.utcfromtimestamp() is an in-built Python class used to represent the time in UTC.

Python datetime.utcfromtimestamp() class is an efficient way of finding dates and times in Python. It represents the time in the UTC DateTime format corresponding to the POSIX timestamp.

The range of timestamps is commonly restricted to years from 1970 through 2038.

Syntax of Python datetime.utcfromtimestamp() Class

datetime.utcfromtimestamp(timestamp)

Parameters

timestamp - A floating point number representing time in seconds since a particular event occurred.

Return

This class does not return a value.

Example 1: Use the datetime.utcfromtimestamp() Class in Python

from datetime import datetime

datetime_object = datetime.utcfromtimestamp(1471290435.0)

print("The time and date in UTC, depending on the timestamp, is: ", datetime_object)

Output:

The time and date in UTC, depending on the timestamp, is:  2016-08-15 19:47:15

The resulting date and time are naive to the current date and time of the system.

Example 2: Enter Out of Range Values in datetime.utcfromtimestamp() Class

from datetime import datetime

datetime_object = datetime.utcfromtimestamp(1471296735240435.0)

print("The time and date in UTC, depending on the timestamp, is: ", datetime_object)

Output:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    datetime_object = datetime.utcfromtimestamp(1471296735240435.0)
ValueError: year 46625507 is out of range

In version 3.3, an OverflowError is raised if the timestamp is out of the range and not supported by the platform C gmtime() function.

Example 3: Display Components of the datetime.utcfromtimestamp() Class

from datetime import datetime

datetime_object = datetime.utcfromtimestamp(1471290435.0)

print("The time and date in UTC, depending on the timestamp, is: ", datetime_object)

print("year = ", datetime_object.year)

print("month =", datetime_object.month)

print("day =", datetime_object.day)

print("hour =", datetime_object.hour)

print("minute =", datetime_object.minute)

print("second =", datetime_object.second)

Output:

The time and date in UTC, depending on the timestamp, is:  2016-08-15 19:47:15
year =  2016
month = 8
day = 15
hour = 19
minute = 47
second = 15

We can use the . dot notation to access specific parts of the datetime object.