gpt4 book ai didi

python - utcfromtimestamp 的相反函数?

转载 作者:太空宇宙 更新时间:2023-11-04 00:03:42 25 4
gpt4 key购买 nike

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

关于python - utcfromtimestamp 的相反函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54935647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com