Home > Article > Backend Development > How Can I Accurately Convert Python Datetime Objects to Epoch Time?
Converting Python Datetime to Epoch with strftime: Unveiling Timezone Discrepancies
To obtain the number of seconds since the epoch from a UTC datetime, developers often rely on the strftime function. However, as demonstrated in this question, using strftime('%s') to convert a datetime to epoch can yield inaccurate results due to timezone adjustments.
Why the Discrepancy?
By default, strftime incorporates the system's timezone into its calculations. As a result, it applies an implicit timezone shift, leading to incorrect epoch conversion for datetimes in certain timezones.
Solutions for Accurate Conversion
To avoid timezone-induced inaccuracies, consider these alternative approaches:
datetime.datetime(2012, 4, 1, 0, 0).timestamp()
(datetime.datetime(2012, 4, 1, 0, 0) - datetime.datetime(1970, 1, 1)).total_seconds()
Caution against Using strftime('%s')
It's crucial to note that the use of strftime('%s') is discouraged for epoch conversion. This is because strftime doesn't explicitly support '%s' as a formatting argument. Its compatibility stems from the underlying system's strftime implementation, which introduces timezone-specific behavior. This inconsistency can lead to incorrect results, making it an unreliable method for portable epoch conversion.
The above is the detailed content of How Can I Accurately Convert Python Datetime Objects to Epoch Time?. For more information, please follow other related articles on the PHP Chinese website!