📜  python datetime to seconds - Python (1)

📅  最后修改于: 2023-12-03 14:45:57.140000             🧑  作者: Mango

Python Datetime to Seconds

In Python, the datetime module provides classes for working with dates and times. We can use it to convert a datetime object to seconds.

To convert a datetime object to seconds, we can first get the timestamp using the timestamp() method, which returns the number of seconds since the Unix epoch (January 1, 1970, UTC). We can then round it to an integer for readability.

Here's an example:

import datetime

dt = datetime.datetime(2022, 1, 1, 0, 0, 0)  # January 1, 2022 at midnight
seconds = round(dt.timestamp())

print(seconds)  # output: 1640995200

In this example, we create a datetime object for January 1, 2022 at midnight. We then call the timestamp() method to get the number of seconds since the Unix epoch, and round it to an integer using the round() function.

We can also use the total_seconds() method to get the total number of seconds represented by a timedelta object. For example:

duration = datetime.timedelta(hours=2, minutes=30, seconds=45)

total_seconds = duration.total_seconds()

print(total_seconds)  # output: 9045.0

In this example, we create a timedelta object representing a duration of 2 hours, 30 minutes, and 45 seconds. We then call the total_seconds() method to get the total number of seconds represented by the timedelta object.

Conclusion

In Python, we can use the datetime module to convert a datetime object to seconds. By using the timestamp() method, we can get the number of seconds since the Unix epoch, and by using the total_seconds() method, we can get the total number of seconds represented by a timedelta object.