Python Datetime.timestamp() Method
-
Syntax of Python
datetime.timestamp()
Method -
Example Codes: Working With the
datetime.timestamp()
Method -
Example Codes: Enter Different DateTime Objects in the
datetime.timestamp()
Method -
Example Codes: Get Timestamp From a Different Time Zone Using the
datetime.timestamp()
Method
Python datetime.timestamp()
method is an efficient way of converting a DateTime object into a timestamp instance. A timestamp is encoded information representing the date and time at which a particular event occurred.
Syntax of Python datetime.timestamp()
Method
datetime.timestamp(datetime_object)
Parameters
datetime_object |
A date and time object that needs to be converted into a timestamp instance. |
Return
The return type of this method is a floating point integer representing a DateTime object.
Example Codes: Working With the datetime.timestamp()
Method
from datetime import datetime
datetime_object = datetime.now()
timestamp = datetime.timestamp(datetime_object)
print("Current time is ", datetime_object)
print("The current time in timestamp format is ", timestamp)
Output:
Current time is 2022-09-01 05:30:24.231005
The current time in timestamp format is 1662010224.231005
Note that the above timestamp represents the number of seconds between the current time and January 1, 1970, at UTC.
Example Codes: Enter Different DateTime Objects in the datetime.timestamp()
Method
from datetime import datetime
past_date = "23.02.0001 09:12:00"
datetime_object = datetime.strptime(past_date, "%d.%m.%Y %H:%M:%S")
timestamp = datetime_object.timestamp()
print(timestamp)
future_date = "23.02.9989 09:12:00"
datetime_object = datetime.strptime(future_date, "%d.%m.%Y %H:%M:%S")
timestamp = datetime_object.timestamp()
print(timestamp)
Output:
-62130984480.0
253059844320.0
On many platforms, the above code may raise an OverflowError
or OSError
exception for times far in the past or the future.
Example Codes: Get Timestamp From a Different Time Zone Using the datetime.timestamp()
Method
from datetime import datetime
import pytz
datetime_object = datetime.now()
timezone = pytz.timezone("Asia/Tokyo")
dtzone = timezone.localize(datetime_object)
print("The time Zone is ", dtzone.tzinfo)
print("Datetime: ", dtzone)
timestamp = dtzone.timestamp()
print("The timestamp in the current timezone is ", datetime_object.timestamp())
print("The timestamp in a different timezone is ", timestamp)
Output:
The time Zone is Asia/Tokyo
Datetime: 2022-09-01 05:54:25.952874+09:00
The timestamp in the current timezone is 1662011665.952874
The timestamp in a different timezone is 1661979265.952874
The above code can easily get the timestamp from any timezone.
Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.
LinkedIn