与 utcfromtimestamp 相反的函数?

use*_*395 6 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)
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 7

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
Run Code Online (Sandbox Code Playgroud)

timestamp-->fromtimestamp也是往返:

asFloat = start.timestamp()
startDifferent = DT.datetime.fromtimestamp(asFloat)
print(startDifferent)
# 2000-01-01 00:00:00
Run Code Online (Sandbox Code Playgroud)

没有直接从 a到时间戳utc的等效项。最接近的等效项是.timestampdatetime.datetimecalendar.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
Run Code Online (Sandbox Code Playgroud)

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