简体   繁体   English

在 python 中将 YYYYDDMM 更改为 YYYYMMDD

[英]change YYYYDDMM to YYYYMMDD in python

I have a df with dates in a column converted to a datetime.我有一个 df,列中的日期转换为日期时间。 the current format is YYYYDDMM.当前格式为 YYYYDDMM。 I need this converted to YYYYMMDD.我需要将其转换为 YYYYMMDD。 I tried the below code but it does not change the format and still gives me YYYYDDMM.我尝试了下面的代码,但它没有改变格式,仍然给我 YYYYDDMM。 the end goal is to subtract 1 business day from the effective date but the format needs to be in YYYYMMDD to do this otherwise it subtracts 1 day from the M and not D. can someone help?最终目标是从生效日期中减去 1 个工作日,但格式需要为 YYYYMMDD 才能执行此操作,否则它会从 M 而不是 D 中减去 1 天。有人可以帮忙吗?

filtered_df['Effective Date'] = pd.to_datetime(filtered_df['Effective Date'])
# Effective Date = 20220408 (4th Aug 2022 for clarity) 
filtered_df['Effective Date new'] = filtered_df['Effective Date'].dt.strftime("%Y%m%d")
# Effective Date new = 20220408

desired output -- > Effective Date new = 20220804

I like to use the datetime library for this purpose.我喜欢为此目的使用datetime库。 You can use strptime to convert a string into the datetime object and strftime to convert your datetime object to the new string.您可以使用strptime将字符串转换为日期时间 object 和strftime将日期时间 object 转换为新字符串。

from datetime import datetime
def change_date(row):
    row["Effective Date new"] = datetime.strptime(row["Effective Date"], "%Y%d%m").strftime("%Y%m%d")
    return row
df2 = df.apply(change_date, axis=1)

The output df2 will have Effective Date new as your new column. output df2将新的Effective Date new作为您的新列。

By default, .to_datetime will interpret the input YYYYDDMM as YYYYMMDD, and therefore print the same thing with %Y%m%d as the format.默认情况下, .to_datetime会将输入 YYYYDDMM 解释为 YYYYMMDD,因此以%Y%m%d作为格式打印相同的内容。 You can fix this and make it properly parse days in the month greater than 12 by adding the dayfirst keyword argument.您可以通过添加dayfirst关键字参数来解决此问题并使其正确解析月份中大于 12 的天数。

filtered_df['Effective Date'] = pd.to_datetime(filtered_df['Effective Date'], dayfirst=True)

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

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