如何使用大熊猫分开日期,小时和时区信息?

发布于 2025-01-29 20:16:35 字数 276 浏览 2 评论 0原文

我很好奇如何使用pandas在.csv文件中处理此类信息:

2022-08-11 11:50:01 America/los_angeles

我的目标是提取日期,小时和分钟以及时区信息以进行进一步分析。

我试图使用以下方式提出日期和时间: df ['date'] = pd.to_datetime(df ['dateTime'])。dt.date

但由于字符串在末尾而遇到了错误。除了使用特定索引提取日期和时间之外,还有更好,更快的方法吗?太感谢了。

I'm curious about how to use pandas to deal with this sort of info in a .csv file:

2022-08-11 11:50:01 America/Los_Angeles

My goal is to extract the date, hour and minute, and the timezone info for further analysis.

I have tried to lift out the date and time using:
df['Date'] = pd.to_datetime(df['datetime']).dt.date

but got an error because of the string at the end. Other than extracting the date and time using specific indices, is there any better and quicker way? Thank you so much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷清清 2025-02-05 20:16:35

Pandas无法处理具有不同时区的DateTime列。您可以首先分组datetimetimezone在单独的列中:

df[['datetime', 'timezone']] = df['datetime'].str.rsplit(' ', n=1, expand=True)
df['datetime'] = pd.to_datetime(df['datetime']) # this column now has the datetime64[ns] type

现在您可以执行以下操作:

df['date_only'] = df['datetime'].dt.date

如果要在中表达所有本地日期/时间America/los_angeles时间:

df['LA_datetime'] = df.apply(lambda x: x['datetime'].tz_localize(tz=x['timezone']).tz_convert('America/Los_Angeles'), axis = 1)

您可以将更改为您喜欢的时区。

pandas cannot handle a datetime column with different timezones. You can start by splitting the datetime and timezone in separate columns:

df[['datetime', 'timezone']] = df['datetime'].str.rsplit(' ', n=1, expand=True)
df['datetime'] = pd.to_datetime(df['datetime']) # this column now has the datetime64[ns] type

Now you are able to do the following:

df['date_only'] = df['datetime'].dt.date

If you want to express all local date/times in America/Los_Angeles time:

df['LA_datetime'] = df.apply(lambda x: x['datetime'].tz_localize(tz=x['timezone']).tz_convert('America/Los_Angeles'), axis = 1)

You can change America/Los_Angeles to the timezone of your liking.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文