[英]Converting all the datetime columns of a variable Pandas DataFrame into a different timezone
I have to deal with a Pandas DataFrame that can be composed by different datetime columns (they can vary, I can have 0..N datetime cols).我必须处理可以由不同日期时间列组成的 Pandas DataFrame(它们可以不同,我可以有 0..N 个日期时间列)。 I know that each datetime column timezone is UTC and I need to convert their data to another timezone.我知道每个日期时间列时区都是 UTC,我需要将它们的数据转换为另一个时区。 If I do as follows:如果我这样做:
df['a_datetime_column'].dt.tz_localize('UTC').dt.tz_convert('my_timezone')
it works but I need to know in advance the datetime column names (ok, I could get them in some way).它有效,但我需要提前知道日期时间列名称(好吧,我可以通过某种方式获得它们)。
Is there a specific way to do this conversion on all the DataFrame at once independently from the composition of its columns?是否有一种特定的方法可以独立于其列的组成同时对所有 DataFrame 进行这种转换?
查看select_dtypes
,您可以使用它仅选择datetime64[ns]
列并将您的tz_convert
应用于这些列:
df.select_dtypes(inlcude=["datetime64[ns]"]).dt.tz_localize('UTC').dt.tz_convert('my_timezone')
You can loop over the columns which have datetime type:您可以遍历具有日期时间类型的列:
for col,dtyp in df.dtypes.iteritems():
if dtyp == 'datetime64[ns]':
df[col] = df[col].dt.tz_localize('UTC').dt.tz_convert('my_timezone')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.