fromtimestamp() Function Of Datetime.date Class In Python
fromtimestamp() function in Python is used to return the date corresponding to a specified timestamp. A timestamp typically represents the number of seconds since January 1, 1970, known as the Unix epoch. This function is a class method of the datetime.date class, and it converts a given timestamp into a human-readable date format. The timestamp can range from the year 1970 to the year 2038.
Example: Getting a date corresponding to an Epoch & Unix Timestamp
import datetime
import time
t = time.time()
print(t)
d = datetime.date.fromtimestamp(t);
print(d);
Output
1746883699.9585874 2025-05-10
Explanation:
- time.time() is used to fetch the current timestamp.
- datetime.date.fromtimestamp() converts the timestamp into a date. The result is printed as a human-readable date, corresponding to the timestamp.
Syntax
@classmethod fromtimestamp(timestamp)
The @classmethod decorator is used to define fromtimestamp as a class method that can be called on the class itself, rather than an instance of the class.
Parameters:
- timestamp: The specified timestamp for which the date is to be returned. It represents the number of seconds since January 1, 1970 (the Unix epoch).
Return Value: The function returns a date object corresponding to the provided timestamp.
Examples fromtimestamp() Function
Example 1: Getting a date corresponding to a specified timestamp.
This example demonstrates how to use the fromtimestamp() function to convert a predefined timestamp (in this case, the timestamp 1323456464) into its corresponding date.
import datetime
import time
t = 1323456464;
d = datetime.date.fromtimestamp(t);
print(d);
Output
2011-12-09
Explanation:
- Here, we define a specific timestamp (1323456464), which represents a specific point in time.
- The datetime.date.fromtimestamp() function converts the timestamp into the corresponding date. The date is printed in a human-readable format.
Example 2: Getting a Date for a Future Timestamp
This example demonstrates how to get a date corresponding to a future Unix timestamp (for example, a date in 2025).
import datetime
t = 1735689600
d = datetime.date.fromtimestamp(t)
print(d)
Output
2025-01-01
Explanation: The timestamp 1735689600 represents January 1, 2025. The fromtimestamp() method converts this timestamp to the corresponding date.
Example 3: Convert a Timestamp Representing a Specific Date
This example demonstrates converting a timestamp for a specific date in the past.
import datetime
t = 1312136400
d = datetime.date.fromtimestamp(t)
print(d)
Output
2011-07-31
Explanation:
- t is a UNIX timestamp representing seconds since Jan 1, 1970 (UTC).
- fromtimestamp(t) converts it to a date object (year, month, day).
- It prints: 2011-07-31 (based on the timestamp and system's local time zone).