简体   繁体   English

将日期和小时转换为日期时间 python pandas

[英]convert date and hour to datetime python pandas

Using Pyhon 3.8, pandas 1.1.2使用 Pyhon 3.8,pandas 1.1.2

MRE:雷:

df = pd.DataFrame({"date":["2020-07-20", "2020-07-20", "2020-07-20", "2020-07-20"],
                   "hour":["1", "2", "3", "4"]})

df["datetime"]  = df["date"] + " " + df["hour"]

This creates dataframe that looks like this:这将创建如下所示的数据框:

    date       hour     datetime
0   2020-07-20  1   2020-07-20 1
1   2020-07-20  2   2020-07-20 2
2   2020-07-20  3   2020-07-20 3
3   2020-07-20  4   2020-07-20 4

I want to make datetime column an actual datetime object.我想让 datetime 列成为实际的 datetime 对象。

Desired output would be期望的输出是

    date       hour     datetime
0   2020-07-20  1   2020-07-20 01:00:00
1   2020-07-20  2   2020-07-20 02:00:00
2   2020-07-20  3   2020-07-20 03:00:00
3   2020-07-20  4   2020-07-20 04:00:00

I want to use this data for plotting a time series graph.我想使用这些数据来绘制时间序列图。 datetime format doesn't need to be in specific format as long as it knows increasing order when plotting using plotly.日期时间格式不需要采用特定格式,只要它在使用 plotly 绘图时知道递增顺序即可。

Thanks in advance!提前致谢!

Use pandas.to_datetime after zfill :pandas.to_datetime之后使用zfill

df["datetime"]  = df["date"] + " " + df["hour"].str.zfill(2)
pd.to_datetime(df["datetime"])

Output:输出:

0   2020-07-20 01:00:00
1   2020-07-20 02:00:00
2   2020-07-20 03:00:00
3   2020-07-20 04:00:00
Name: datetime, dtype: datetime64[ns]

Another way其它的办法

#pad df.hour with 0 on the left

s=df.hour.str.pad(width=2, side='left', fillchar='0')

#concat using df.str.cat

df['datetime']=pd.to_datetime(df['date'].str.cat(s+":00:00", sep=' '))

    date      hour        datetime
0  2020-07-20    1  2020-07-20 01:00:00
1  2020-07-20    2  2020-07-20 02:00:00
2  2020-07-20    3  2020-07-20 03:00:00
3  2020-07-20    4  2020-07-20 04:00:00

Another way using datetime module in python.在 python 中使用 datetime 模块的另一种方法。

strftime converts datetime to str, strftime将日期时间转换为 str,
strptime converts str to datetime. strptime将 str 转换为日期时间。

base_df["datetime"] = base_df["datetime"].apply(lambda row: datetime.strptime(row, "%Y-%m-%d %H"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM