简体   繁体   English

Python:如何将 unixtimestamp 和 timezone 转换为 datetime 对象?

[英]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 argument tz 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 class tzinfo subclass, and the timestamp is converted to tz 's time zone.否则tz必须是类tzinfo子类的实例,时间戳转换为tz的时区。 In this case the result is equivalent to tz.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.这个问题很老了,但我想给出一个更全面的答案。

  1. 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 是格林威治标准时间,没有夏令时调整。)

  2. 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

  3. 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.

相关问题 如何将字符串转换为具有相关时区的python datetime对象? - How do I convert a string to a python datetime object with a relevant timezone? 如何在Django Rest Framework中将Python日期时间对象转换为特定时区? - How to convert Python datetime object to specific timezone in Django Rest Framework? Python - 如何将日期时间对象转换为列中作为字符串给出的时区? - Python - How to convert datetime object to timezone given as string in a column? 如何将不带时区的datetime字符串转换为python中带时区的另一个datetime? - How to convert datetime string without timezone to another datetime with timezone in python? 如何将 python 的 datetime.tzinfo 对象转换为钟摆的 Timezone 对象? - How to convert a python's datetime.tzinfo object to a pendulum's Timezone object? 如何使时区感知日期时间 object - How to make a timezone aware datetime object python 将带时区的时间戳转换为日期时间 - python convert timestamp with timezone to datetime 蟒蛇。 将datetime对象转换为包含时区的字符串 - Python. Convert datetime object to string with timezone included 将python datetime与timezone一起转换为string - convert python datetime with timezone to string 如何将未知时区的字符串日期时间转换为python中的时间戳 - how to convert a string datetime with unknown timezone to timestamp in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM