utcfromtimestamp()的相反功能是什么?

在以下示例中可以看到,timestamp()显然没有考虑时区:

import pandas as pd
import datetime
start = pd.datetime(2000, 1, 1, 0, 0, 0)
asFloat = start.timestamp()
startDifferent = datetime.datetime.utcfromtimestamp(asFloat)
startDifferent
Out[8]: datetime.datetime(1999, 12, 31, 23, 0)

最佳答案

utctimetuple-> calendar.timegm-> utcfromtimestamp往返:

import calendar
import datetime as DT
start = DT.datetime(2000, 1, 1, 0, 0, 0)

utc_tuple = start.utctimetuple()
utc_timestamp = calendar.timegm(utc_tuple)
startDifferent = DT.datetime.utcfromtimestamp(utc_timestamp)
print(startDifferent)
# 2000-01-01 00:00:00


timestamp-> fromtimestamp也是往返:

asFloat = start.timestamp()
startDifferent = DT.datetime.fromtimestamp(asFloat)
print(startDifferent)
# 2000-01-01 00:00:00


没有与utc等效的timestamp,它直接从datetime.datetime变为时间戳。最接近的等效项是calendar.timegm(date.utctimetuple())



这大致描述了方法之间的关系:

                o------------o
                |            |  DT.datetime.utcfromtimestamp (*)
                |            |<-----------------------------------o
                |            |                                    |
                |            |  DT.datetime.fromtimestamp         |
                |  datetime  |<-------------------------------o   |
                |            |                                |   |
                |            |    .timestamp                  |   |
                |            |----------------------------o   |   |
                |            |                            |   |   |
                o------------o                            |   |   |
                   |   ^                                  |   |   |
        .timetuple |   |                                  |   |   |
 .utctimetuple (*) |   | DT.datetime(*tup[:6])            |   |   |
                   v   |                                  v   |   |
                o------------o                          o------------o
                |            |-- calendar.timegm (*) -->|            |
                |            |                          |            |
                |            |---------- time.mktime -->|            |
                |  timetuple |                          |  timestamp |
                |            |<-- time.localtime -------|            |
                |            |                          |            |
                |            |<-- time.gmtime (*)-------|            |
                o------------o                          o------------o


(*)将其输入解释为UTC,并返回应解释为UTC的输出。

07-26 06:18