Python tz感知字符串pd.to_datetime有时返回datetime而不是时间戳 我有下面的pandas数据框,数据是str格式的 由于夏令时,数据在第1行和第2行之间的时间偏移发生了变化 当我用apply按行转换它时,它也可以工作 >数据['con

Python tz感知字符串pd.to_datetime有时返回datetime而不是时间戳 我有下面的pandas数据框,数据是str格式的 由于夏令时,数据在第1行和第2行之间的时间偏移发生了变化 当我用apply按行转换它时,它也可以工作 >数据['con,python,pandas,datetime,Python,Pandas,Datetime,tz感知字符串pd.to_datetime有时返回datetime而不是时间戳 我有下面的pandas数据框,数据是str格式的 由于夏令时,数据在第1行和第2行之间的时间偏移发生了变化 当我用apply按行转换它时,它也可以工作 >数据['converted']=数据['timestamp']。应用(pd.to_datetime) >>>数据['type']=数据['converted']。应用(类型) >>>资料 时间戳转换类型 0 2017-03-10 14:58:51-06:00

tz感知字符串pd.to_datetime有时返回datetime而不是时间戳
  • 我有下面的pandas数据框,数据是str格式的
  • 由于夏令时,数据在第1行和第2行之间的时间偏移发生了变化
  • 当我用apply按行转换它时,它也可以工作
>数据['converted']=数据['timestamp']。应用(pd.to_datetime)
>>>数据['type']=数据['converted']。应用(类型)
>>>资料
时间戳转换类型

0 2017-03-10 14:58:51-06:00 2017-03-10 14:58:51-06:00一旦在一列中有具有不同UTC偏移量(或时区)的时间戳,则整个列的数据类型将为“object”类型-无论您是将整个列(第一个示例)或元素(第二个示例)从字符串转换为_datetime。不知道为什么在这两个示例中会得到来自不同类的实例。旁注:另一种方法是使用
pd.to_datetime(col,UTC=True)
将所有内容解析为UTC。使用UTC=True标志可以将数据加载到所需的格式。然后我使用tz_convert将其更改回原始时区。谢谢很好,没有想到这个^^^(只要你知道时区)。一旦你在一列中有不同UTC偏移量(或时区)的时间戳,整个列的数据类型将是“object”类型——不管你是将整个列(第一个示例)还是元素(第二个示例)从string转换为\u datetime。不知道为什么在这两个示例中会得到来自不同类的实例。旁注:另一种方法是使用
pd.to_datetime(col,UTC=True)
将所有内容解析为UTC。使用UTC=True标志可以将数据加载到所需的格式。然后我使用tz_convert将其更改回原始时区。谢谢太好了,没想到这个^^^(只要你知道时区)。
>>> data
                   timestamp
0  2017-03-10 14:58:51-06:00
1  2017-03-10 14:59:59-06:00
2  2017-03-13 08:30:00-05:00
3  2017-03-13 08:30:01-05:00

>>> type(data.loc[0, 'timestamp'])
<class 'str'>
>>> data['converted'] = pd.to_datetime(data['timestamp'])
>>> data['type'] = data['converted'].apply(type)
>>> data
                   timestamp                  converted                         type
0  2017-03-10 14:58:51-06:00  2017-03-10 14:58:51-06:00  <class 'datetime.datetime'>
1  2017-03-10 14:59:59-06:00  2017-03-10 14:59:59-06:00  <class 'datetime.datetime'>
2  2017-03-13 08:30:00-05:00  2017-03-13 08:30:00-05:00  <class 'datetime.datetime'>
3  2017-03-13 08:30:01-05:00  2017-03-13 08:30:01-05:00  <class 'datetime.datetime'>
>>> pd.to_datetime(data.loc[2:, 'timestamp'])
2   2017-03-13 08:30:00-05:00
3   2017-03-13 08:30:01-05:00
Name: timestamp, dtype: datetime64[ns, pytz.FixedOffset(-300)]
>>> data['converted'] = data['timestamp'].apply(pd.to_datetime)
>>> data['type'] = data['converted'].apply(type)
>>> data
                   timestamp                  converted                                               type
0  2017-03-10 14:58:51-06:00  2017-03-10 14:58:51-06:00  <class 'pandas._libs.tslibs.timestamps.Timesta...
1  2017-03-10 14:59:59-06:00  2017-03-10 14:59:59-06:00  <class 'pandas._libs.tslibs.timestamps.Timesta...
2  2017-03-13 08:30:00-05:00  2017-03-13 08:30:00-05:00  <class 'pandas._libs.tslibs.timestamps.Timesta...
3  2017-03-13 08:30:01-05:00  2017-03-13 08:30:01-05:00  <class 'pandas._libs.tslibs.timestamps.Timesta...