Home  >  Article  >  Backend Development  >  How to Accurately Convert a Python datetime Object to Epoch Time Without Using strftime(\'%s\')?

How to Accurately Convert a Python datetime Object to Epoch Time Without Using strftime(\'%s\')?

DDD
DDDOriginal
2024-11-20 04:53:01291browse

How to Accurately Convert a Python datetime Object to Epoch Time Without Using strftime('%s')?

Converting Python datetime to Epoch Using strftime

Originally, the aim was to convert a UTC time into the number of seconds since the epoch using strftime. However, upon using strftime with the '%s' format, the resulting value differed from the expected epoch count by an hour. Investigating this discrepancy revealed that strftime incorporates the system time and adjusts for time zone differences, although datetime is believed to be naive.

Solution

To overcome this issue, consider the following alternatives:

Python 3.3 and Later

  • Utilize the timestamp() method of datetime:

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

Python 3.2 and Earlier

  • Explicitly calculate the difference between the given datetime and the epoch datetime:

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

Caution: Avoiding strftime('%s')

It's crucial to note that datetime does not officially support the '%s' format specifier for strftime. Its current functionality is due to the interaction with the system's strftime implementation, which adjusts for time zone differences. Using strftime('%s') can lead to inconsistent results due to potential time zone variations.

The above is the detailed content of How to Accurately Convert a Python datetime Object to Epoch Time Without Using strftime(\'%s\')?. 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