在Pandas中将DDMMMYYYY格式日期字符串列转为YYYYMMDD格式
Pandas日期格式转换:DDMMMYYYY转YYYYMMDD
需要将Pandas DataFrame中以字符串存储、格式为DDMMMYYYY(如31Oct2023)的日期列,转换为YYYYMMDD格式(如20231031)。
示例数据
| 序号 | GivenInput | ExpectedDates |
|---|---|---|
| 0 | 31Jan2023 | 20230131 |
| 1 | 28Feb2023 | 20230228 |
| 2 | 31Mar2023 | 20230331 |
| 3 | 30Apr2023 | 20230430 |
| 4 | 31May2023 | 20230531 |
| 5 | 30Jun2023 | 20230630 |
| 6 | 31Jul2023 | 20230731 |
| 7 | 31Aug2023 | 20230831 |
| 8 | 30Sep2023 | 20230930 |
| 9 | 31Oct2023 | 20231031 |
| 10 | 30Nov2023 | 20231130 |
| 11 | 31Dec2023 | 20231231 |
| 12 | 31Jan2024 | 20240131 |
| 13 | 29Feb2024 | 20240229 |
| 14 | 31Mar2024 | 20240331 |
| 15 | 30Apr2024 | 20240430 |
| 16 | 31May2024 | 20240531 |
加载示例数据代码
import pandas as pd from io import StringIO s = """ GivenInput 31Jan2023 28Feb2023 31Mar2023 30Apr2023 31May2023 30Jun2023 31Jul2023 31Aug2023 30Sep2023 31Oct2023 30Nov2023 31Dec2023 31Jan2024 29Feb2024 31Mar2024 30Apr2024 31May2024 """ s = s.strip() df = pd.read_csv(StringIO(s)) print(df)
转换方案
核心代码
# 执行日期格式转换 df['ConvertedDates'] = pd.to_datetime(df['GivenInput'], format='%d%b%Y').dt.strftime('%Y%m%d') # 查看转换结果 print(df[['GivenInput', 'ConvertedDates']])
代码说明
pd.to_datetime(df['GivenInput'], format='%d%b%Y'):按照DDMMMYYYY格式将字符串列解析为Pandas日期时间类型.dt.strftime('%Y%m%d'):将日期时间类型重新格式化为YYYYMMDD的字符串格式
内容的提问来源于stack exchange,提问作者CypherX
相关产品推荐
相关产品推荐

