Methods to Convert Datetime Object to Seconds
We can convert Datetime Object To Seconds using different methods:
1. Using total_seconds() Method
We can use total_seconds() method to convert a datetime object to seconds. To use total_seconds() method we must convert our datetime object into a timedelta object. Timedelta is an object that represent the difference between two dates or times.
Here, we are creating a datetime object using strptime() method available in datetime module, we calculated the timedelta between our datetime and reference datetime objects, and then we converted this timedelta into seconds.
Python3
import datetime # Define a time string time = "01:01:09" date_time = datetime.datetime.strptime(time, "%H:%M:%S" ) # Calculate the difference from the reference datetime a_timedelta = date_time - datetime.datetime( 1900 , 1 , 1 ) seconds = a_timedelta.total_seconds() print (seconds) |
Output:
3669.0
2. Using timestamp() Method
We can use timestamp() method from datetime module in python to convert a datetime object to seconds. The timestamp() method returns a floating-point value representing the number of seconds, including fractions of a second.
Here, we are creating a datetime object using today() function, this function will return the current local date and time. Then we converted the datetime object to seconds using timestamp() method. This method converts the given datetime object to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).
Python3
from datetime import datetime # Get current date and time dt = datetime.today() seconds = dt.timestamp() print (seconds) |
Output:
1706977614.491229
3. Using calendar.timegm() Method
We can use calendar.timegm() Method to convert a datetime object to seconds. This function converts the UTC time tuple to the number of seconds since the epoch (1970-01-01 00:00:00 UTC) and returns the result as an integer.
Here, we are creating a datetime object using today() function, this function will return the current local date and time. We then use the utctimetuple() method of the datetime object to retrieve a time tuple representing the dt object.
The utctimetuple() method returns a time tuple in the format (year, month, day, hour, minute, second, weekday, yearday, isdst). We pass the UTC time tuple obtained from dt to the calendar.timegm() method.
Python3
from datetime import datetime import calendar # Get current date and time dt = datetime.today() seconds = calendar.timegm(dt.utctimetuple()) print (seconds) |
Output:
1706977627
Convert A Datetime Object To Seconds
A datetime object in Python is a data structure used to represent dates and times. With datetime, developers can perform various operations on dates and times, making it a fundamental module for handling temporal data in Python programs.