与utcfromtimestamp相反的函数?

2024-10-03 15:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

Tags: 函数importpandasdatetimeasoutstarttimestamp
1条回答
网友
1楼 · 发布于 2024-10-03 15:26:31

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格式的输出。你知道吗

相关问题 更多 >