Python Pandas将带有时区的Unix时间戳转换为datetime [英] Python pandas convert unix timestamp with timezone into datetime

查看:141
本文介绍了Python Pandas将带有时区的Unix时间戳转换为datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

df = pd.DataFrame({'unix_utc_ts': [1503007204222, 1503007210206, 1503007215121,
    1503007220475], 'tz': ['+0000', '+0100', 'CEST', 'EEST']})

我想将unix时间戳转换为带时区的datetime,所以我想要这样的东西:

And I want to convert unix timestamps into datetime with timezone, so I want something like this:

df['local_ts'] = pd.to_datetime(df['unix_utc_ts'], unit='ms', tz=df['tz'])

上面的代码不起作用。如果没有 tz 参数,我会得到:

The above code doesn't work. Without the tz argument I get this:

      tz    unix_utc_ts                  utc_ts
0  +0000  1503007204222 2017-08-17 22:00:04.222
1  +0100  1503007210206 2017-08-17 22:00:10.206
2   CEST  1503007215121 2017-08-17 22:00:15.121
3   EEST  1503007220475 2017-08-17 22:00:20.475

当然我希望将时区包含在日期时间中,所以我要使用以下数据框:

But of course I want timezone to be included in datetime, so I want this dataframe:

      tz    unix_utc_ts                  utc_ts                local_ts
0  +0000  1503007204222 2017-08-17 22:00:04.222 2017-08-17 22:00:04.222
1  +0100  1503007210206 2017-08-17 22:00:10.206 2017-08-17 23:00:10.206
2   CEST  1503007215121 2017-08-17 22:00:15.121 2017-08-18 00:00:15.121
3   EEST  1503007220475 2017-08-17 22:00:20.475 2017-08-18 01:00:20.475

我已经搜索并阅读了很多stackoverflow问题,但找不到任何有效答案:(

I've searched and read lots of stackoverflow questions but didn't find any working answer :(

谢谢!

推荐答案

使用应用 tz_localize 转换每一行:

import pandas as pd
df = pd.DataFrame({'unix_utc_ts': [1503007204222, 1503007210206, 1503007215121,
1503007220475], 'tz': ['CEST', 'EEST', 'CEST', 'EEST']})

df['datetime_utc'] = pd.to_datetime(df['unix_utc_ts'], unit='ms')
df['datetime_local'] = df.apply(lambda x: x['datetime_utc'].tz_localize(x['tz']), axis=1)

但是,您的时区格式将会出现问题。 Pytz 用于映射时区字符串,而您列出的时区字符串不匹配(此处是我发现的列表)。因此,您必须从时区名称映射到Pytz的映射。

However, you are going to have an issue with the format of your timezones. Pytz is used to map timezone strings, and the ones you have listed don't match (here is a listing I found of them). So you'll have to make a mapping from your timezone names to Pytz's.

这篇关于Python Pandas将带有时区的Unix时间戳转换为datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆