Home >Backend Development >Python Tutorial >How to Accurately Convert Python Datetime Objects to Epoch Timestamps?

How to Accurately Convert Python Datetime Objects to Epoch Timestamps?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 09:34:03555browse

How to Accurately Convert Python Datetime Objects to Epoch Timestamps?

Converting Python Datetime to Epoch with strftime

When converting a Python datetime object to the number of seconds since epoch using the strftime('%s') format, you might encounter an unexpected result. Instead of the correct number of seconds from the epoch, you may get a value that differs by an hour. This is because strftime considers the system timezone and applies a timezone shift.

Solution:

To avoid this issue and obtain the correct epoch timestamp, there are several options available:

Python 3.3 and Later:

  • Use the timestamp() method:

    >>> datetime.datetime(2012, 4, 1, 0, 0).timestamp()
    1333234800.0

Python 3.2 or Earlier:

  • Perform the conversion explicitly:

    >>> (datetime.datetime(2012, 4, 1, 0, 0) - datetime.datetime(1970, 1, 1)).total_seconds()
    1333238400.0

Avoid Using strftime('%s'):

It's important to note that %s is not officially supported by Python's strftime function. Its functionality is dependent on the system's strftime implementation, which may vary across different platforms and introduce timezone discrepancies. Therefore, it's recommended to use the methods mentioned above for accurate epoch timestamp conversions.

The above is the detailed content of How to Accurately Convert Python Datetime Objects to Epoch Timestamps?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn