如何在Python中将保存为整数类型的CSV文件中的时间数据转换为日期时间。

huangapple go评论64阅读模式
英文:

How to convert time data which saved as integer type in csv file into datetime in python

问题

import pandas as pd

# Assuming df_NPA_2020 is your DataFrame and 'TIME' is the column with integer time data
df_NPA_2020['ch_time'] = df_NPA_2020['TIME'].apply(lambda x: '{:02d}:{:02d}:{:02d}'.format(x // 3600, (x % 3600) // 60, x % 60))

使用上述代码片段,您可以将整数类型的时间数据转换为日期时间格式,将结果存储在名为'ch_time'的新列中。

英文:

I have csv file and in 'Time' column, time data is saved in integer type like

7
20
132
4321
123456
...

and I have to convert datatime in python like

00:00:07
00:00:20
00:01:32
00:43:21
12:34:56
...

and size of data is almost 250,000,,,

How do I convert this number to a datetime?

I tried but failed

change_time=str(int(df_NPA_2020['TIME'])).zfill(6)
change_time=change_time[:2]+":"+change_time[2:4]+":"+change_time[4:]
change_time

and

change_time=df_NPA_2020['ch_time'] = df_NPA_2020['TIME'].apply(lambda x: pd.to_datetime(str(x), format='%H:%M:%S'))

答案1

得分: 4

你差不多到了。你需要使用.astype(str)方法将一个列转换为字符串,而不是str(df_NPA_2020['TIME'])。后者类似于print

df_NPA_2020['ch_time'] = pd.to_datetime(df_NPA_2020['TIME'].astype(str).str.zfill(6), format='%H%M%S').dt.time
print(df_NPA_2020)

# 输出
     TIME             ch_time
0       7 1900-01-01 00:00:07
1      20 1900-01-01 00:00:20
2     132 1900-01-01 00:01:32
3    4321 1900-01-01 00:43:21
4  123456 1900-01-01 12:34:56
英文:

You're almost there. You have to use .astype(str) method to convert a column as string and not str(df_NPA_2020['TIME']). The latter is like a print.

df_NPA_2020['ch_time'] = pd.to_datetime(df_NPA_2020['TIME'].astype(str).str.zfill(6), format='%H%M%S').dt.time
print(df_NPA_2020)

# Output
     TIME             ch_time
0       7 1900-01-01 00:00:07
1      20 1900-01-01 00:00:20
2     132 1900-01-01 00:01:32
3    4321 1900-01-01 00:43:21
4  123456 1900-01-01 12:34:56

答案2

得分: 2

将数字解析为日期时间,然后格式化它:

import pandas as pd

df = pd.DataFrame([7, 20, 132, 4321, 123456], columns=['Time'])
print(df)
df.Time = df.Time.apply(lambda x: pd.to_datetime(f'{x:06}', format='%H%M%S')).dt.strftime('%H:%M:%S')
print(df)

输出:

     Time
0       7
1      20
2     132
3    4321
4  123456
       Time
0  00:00:07
1  00:00:20
2  00:01:32
3  00:43:21
4  12:34:56
英文:

Parse the number into a datetime, then format it:

import pandas as pd

df = pd.DataFrame([7,20,132,4321,123456], columns=['Time'])
print(df)
df.Time = df.Time.apply(lambda x: pd.to_datetime(f'{x:06}', format='%H%M%S')).dt.strftime('%H:%M:%S')
print(df)

Output:

     Time
0       7
1      20
2     132
3    4321
4  123456
       Time
0  00:00:07
1  00:00:20
2  00:01:32
3  00:43:21
4  12:34:56

huangapple
  • 本文由 发表于 2023年2月10日 15:02:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定