Converting datetime.date to UTC Timestamp in Python
When dealing with dates in Python, the need arises to convert them to UTC timestamps for various applications. However, using conventional methods like datetime.datetime.utcfromtimestamp(time.mktime(d)) may lead to incorrect results.
Converting a UTC Date to Seconds Since Epoch
For a date d represented in UTC, the correct formula to convert it to seconds since epoch is:
timestamp1 = calendar.timegm(d.timetuple())
This method ensures the resulting timestamp represents the date in UTC.
Converting a Local Time Date to Seconds Since Epoch
If the date d is in the local timezone, using mktime() may yield incorrect results. To remedy this, we can use:
timestamp2 = time.mktime(d.timetuple())
However, note that timestamp1 and timestamp2 may differ if the local midnight differs from UTC midnight.
Converting datetime.date in UTC without calendar.timegm()
To convert a datetime.date object directly to a UTC timestamp, you can use the following formulae:
timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY timestamp = (utc_date - date(1970, 1, 1)).days * DAY
Converting datetime.datetime in UTC to POSIX Timestamp
For a datetime.datetime object already in UTC, the following methods are available:
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
Converting an Aware datetime Object to POSIX Timestamp
For an aware datetime object (datetime with timezone information), the following approach is recommended:
timestamp = dt.timestamp() # Python 3.3+ timestamp = (dt - epoch) / timedelta(seconds=1) # Python 3 timestamp = (dt - epoch) // timedelta(seconds=1) # Python 3 integer timestamp
The above is the detailed content of How to Accurately Convert Python `datetime.date` and `datetime.datetime` Objects to UTC Timestamps?. For more information, please follow other related articles on the PHP Chinese website!