与utcfromtimestamp相反的功能?

时间:2019-02-28 23:03:09

标签: python datetime

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)

1 个答案:

答案 0 :(得分:3)

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的输出。