[英]Python: How to convert unixtimestamp and timezone into datetime object?
I have a csv file with the datetime in unixtimestamp format with milliseconds and timezone information in milliseconds as well.我有一个 csv 文件,日期时间为 unixtimestamp 格式,毫秒和时区信息也以毫秒为单位。 I want to convert this into a more usable datetime format for further processing.
我想将其转换为更有用的日期时间格式以供进一步处理。
For example, the time is 1437323953822
and timezone is -14400000
.例如,时间是
1437323953822
,时区是-14400000
。
I can convert the timestamp into a datetime by using我可以通过使用将时间戳转换为日期时间
datetime.datetime.fromtimestamp(1437323953822/1000)
But how do I now incorporate the timezone which is -4 UTC time from what I know.但是我现在如何合并时区,根据我所知,时区为 -4 UTC 时间。
(-14400000 / 1000 / 60 / 60) = -4
How do I use this timezone to get the actual time?我如何使用这个时区来获取实际时间?
fromtimestamp
can also take another parameter for the timezone, a subclass of tzinfo
: fromtimestamp
还可以为时区采用另一个参数,即tzinfo
的子类:
classmethod datetime.fromtimestamp(timestamp[, tz])
Return the local date and time corresponding to the POSIX timestamp, such as is returned by
time.time()
.返回 POSIX 时间戳对应的本地日期和时间,如
time.time()
返回。 If optional argumenttz
is None or not specified, the timestamp is converted to the platform's local date and time, and the returned datetime object is naive.如果可选参数
tz
为 None 或未指定,则时间戳将转换为平台的本地日期和时间,并且返回的日期时间对象是幼稚的。Else
tz
must be an instance of a classtzinfo
subclass, and the timestamp is converted totz
's time zone.否则
tz
必须是类tzinfo
子类的实例,时间戳转换为tz
的时区。 In this case the result is equivalent totz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz)).
在这种情况下,结果相当于
tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz)).
fromtimestamp()
already returns your local time ie, you don't need to attach the utc offset if fromtimestamp()
determines it correctly automatically: fromtimestamp()
已经返回您的本地时间,即,如果fromtimestamp()
自动正确确定它,您不需要附加 utc 偏移量:
#!/usr/bin/env python
from datetime import datetime
local_time = datetime.fromtimestamp(1437323953822 * 1e-3)
# -> datetime.datetime(2015, 7, 19, 12, 39, 13, 822000)
fromtimestamp()
may fail in some cases eg, if the local timezone had a different utc offset in the past and fromtimestamp()
does not use a historical timezone database on a given platform (notably, Windows).在某些情况下,
fromtimestamp()
可能会失败,例如,如果本地时区过去有不同的 UTC 偏移量,并且fromtimestamp()
不使用给定平台(特别是 Windows)上的历史时区数据库。 In that case, construct the local time explicitly from utc time and the given utc offset:在这种情况下,根据 utc 时间和给定的 utc 偏移量显式构造本地时间:
#!/usr/bin/env python
from datetime import datetime, timedelta
utc_time = datetime(1970, 1, 1) + timedelta(milliseconds=1437323953822)
utc_offset = timedelta(milliseconds=-14400000)
local_time = utc_time + utc_offset
# -> datetime.datetime(2015, 7, 19, 12, 39, 13, 822000)
Python always expects POSIX Epoch and therefore it is ok to hardcode it. Python 总是期望 POSIX Epoch ,因此可以对其进行硬编码。 The explicit formula may be more precise (no rounding error) and it may accept a wider range of input timestamps (
fromtimestamp()
range depends on platform and may be narrower than the corresponding datetime
range).显式公式可能更精确(没有舍入误差),并且它可以接受更广泛的输入时间戳(
fromtimestamp()
范围取决于平台,并且可能比相应的datetime
范围更窄)。
This question is old but I want to give a slightly more comprehensive answer.这个问题很老了,但我想给出一个更全面的答案。
About the unix timestamp:关于unix时间戳:
The timestamp is the number of seconds (or milliseconds) elapsed since an absolute point in time, midnight of Jan 1 1970 in UTC time.时间戳是从绝对时间点(UTC 时间 1970 年 1 月 1 日午夜)以来经过的秒数(或毫秒)。 (UTC is Greenwich Mean Time without Daylight Savings time adjustments.)
(UTC 是格林威治标准时间,没有夏令时调整。)
fromtimestamp
does convert the unix timestamp to your platform's time. fromtimestamp
确实将 unix 时间戳转换为您平台的时间。 If you are working across different platforms, it is important to set the platform's timezone correctly.如果您在不同平台上工作,正确设置平台的时区很重要。 If you want it to be in UTC instead, then
utcfromtimestamp
should be used instead.如果您希望它使用 UTC,
utcfromtimestamp
。
To answer OP's question directly, the following code will create a timezone based on the offset.要直接回答 OP 的问题,以下代码将根据偏移量创建时区。
from datetime import datetime, timezone, timedelta
ts = int('1604750712')
tz = timezone(-timedelta(hours=4))
print(datetime.fromtimestamp(ts, tz).strftime('%Y-%m-%d %H:%M:%S'))
timezone
object is an concrete class of tzinfo
, I have initiated it with a negative offset of 4 hours from UTC. timezone
对象是tzinfo
一个具体类,我已经用 UTC 4 小时的负偏移量启动了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.