Home > Article > Backend Development > Here are a few title options, keeping in mind the question-and-answer format: **More Direct
Converting datetime Objects to Seconds in Python
Problem:
You have multiple datetime objects and need to calculate the number of seconds that have passed since a fixed time in the past (e.g., January 1, 1970) for each object. While t.toordinal() seems to differentiate only between dates with different days, you aim for a more precise conversion to seconds.
Solution:
For the specific date of January 1, 1970, you have several options:
Convert to a time object and use mktime():
<code class="python">import time time.mktime(t.timetuple())</code>
Use the total_seconds() method of a timedelta object (available in Python 2.7 and later):
<code class="python">from datetime import timedelta (t - datetime.datetime(1970, 1, 1)).total_seconds()</code>
For any other starting date, you need to subtract the two dates to get a timedelta object and then use its total_seconds() function:
<code class="python">from datetime import datetime, timedelta (t - datetime.datetime(2000, 1, 1)).total_seconds()</code>
Remember that the starting date is typically specified in UTC. If your datetime object is not in UTC, convert it before using it, or provide a tzinfo class with the correct offset.
The above is the detailed content of Here are a few title options, keeping in mind the question-and-answer format: **More Direct. For more information, please follow other related articles on the PHP Chinese website!