[英]Convert column of timestamp with a different UTC base to current UTC using Python
我有一個數據框,其時間戳是自2010年1月1日午夜UTC時區以來的秒數。 我需要將它們轉換為當前的UTC時間。 我能夠使用timedelta為給定的行執行此操作,但無法為整個時間戳列實現該行。
# The base of my timestamp is UTC(2010 Jan 1, midnight)
# able to do it for a specific delta i.e. df["timestamp][0]
sec_shift = pd.Timedelta(seconds=201852000)
new_time = datetime.datetime(2010,1,1)+sec_shift
# how do i do this for the entire df["timestamp"] column?
df = pd.DataFrame({"timestamp":[201852000,201852060,201852120,201852180,201852240], "B":[160863892,160864264,160864637,160865009,160865755]})
嘗試這個:
dif = (datetime.datetime(2010,1,1) - datetime.datetime(1970,1,1)).total_seconds()
sec_shift = 4*60*60
pd.to_datetime(df.timestamp + diff + sec_shift, unit='s')
演示:
In [29]: pd.to_datetime(df.timestamp + dif + sec_shift, unit='s')
Out[29]:
0 2016-05-25 10:00:00
1 2016-05-25 10:01:00
2 2016-05-25 10:02:00
3 2016-05-25 10:03:00
4 2016-05-25 10:04:00
Name: timestamp, dtype: datetime64[ns]
PS我建議你使用標准解決方案,例如存儲自UTC時間1月1日1970年午夜UTC(標准UNIX時間戳)以來的秒數 - 這將使您的工作更簡單
您可以將一系列Timedeltas添加到時間戳:
df['date'] = pd.Timestamp('2010-1-1')+pd.to_timedelta(df['timestamp'], unit='s')
例如,
import pandas as pd
df = pd.DataFrame({"timestamp":[201852000,201852060,201852120,201852180,201852240],
"B":[160863892,160864264,160864637,160865009,160865755]})
df['date'] = pd.Timestamp('2010-1-1')+pd.to_timedelta(df['timestamp'], unit='s')
print(df)
產量
B timestamp date
0 160863892 201852000 2016-05-25 06:00:00
1 160864264 201852060 2016-05-25 06:01:00
2 160864637 201852120 2016-05-25 06:02:00
3 160865009 201852180 2016-05-25 06:03:00
4 160865755 201852240 2016-05-25 06:04:00
我提出了這個有效的解決方案,但是如果有更好的解決方案請更新。 找到更好的方法來做這件事會很棒。
# Calculating the seconds between 1/1/1970 - 1/1/2010
# Adding that to the timestamp column to get the seconds from 1/1/1970
seconds_from_2010= (datetime.datetime(2010,01,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
df["new_timestamp"]= pd.to_datetime(df["timestamp"]+seconds_from_2010,unit='s')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.