[英]Delete time minutes from time object python
我在 pandas dataframe 中有一個字段,我想從中截斷分鍾,即將時間轉換為字符串,拆分它並僅保留小時。
The time field in my dataframe is of type object and what I have tried to do is as below (accidents is my pandas dataframe by the way):
for row in range (1, len(accidents)):
hour = row['Time'].strftime("%H").split(":", 1)[0]
例如,我想做的是將 17:45 更改為 17。
事故圖像 Dataframe 如下。
Time object 的數據類型如下。
當我運行上述代碼時,出現錯誤“TypeError: 'int' object is not subscriptable”
我知道這是某種形式的鑄造錯誤,但我不知道如何解決它。 (我對 Python 很陌生)。
如果需要,可以重新生成 csv 文件(此處截斷以僅包含相關字段)。 Accident_Index,Location_Easting_OSGR,Location_Northing_OSGR,經度,緯度,Police_Force,Accident_Severity,Number_of_Vehicles,Number_of_Casualties,日期,Day_of_Week,時間, 200501BS00001,525680,178240,-0.191170,51.4,380096,1/201,1/20,04/ ,17:42
datetime
模塊的strftime()
需要有一個格式參數(請參閱下面的正確用法)。
>>> datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
'08/09/2020, 02:48:25'
(這里有一個好的strftime()
備忘單)
在您的情況下,您似乎只是想獲取小時數。 為此,您應該使用以下格式字符串來獲取小時: "%H"
。 如果您需要將其作為 integer (如果您需要用它進行數學運算),您可以簡單地用int()
包圍它。 如果您只想顯示此數字,則可以將其保留為字符串。 strftime()
默認返回一個字符串。
試試這個代碼:
hour = int(row['Time'].strftime("%H"))
您可以使用時間列的hour
屬性
d = [d for d in pd.date_range(dt.datetime(2020,5,1,2),
dt.datetime(2020,5,3,4), freq="45min")
] # miss some sample times...
# random manipulation of rawIdx so there are some rows where ts is not in rawIdx
df = pd.DataFrame({"Time":d,
"val":[random.randint(0,50) for x in d]})
df["Hour"] = df["Time"].dt.hour
print(df.head().to_string(index=False))
output
Time val Hour
2020-05-01 02:00:00 39 2
2020-05-01 02:45:00 23 2
2020-05-01 03:30:00 9 3
2020-05-01 04:15:00 25 4
2020-05-01 05:00:00 41 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.