[英]How to change Day/Month/Year format to Month/Day/Year in Python
I have a column that the date is in Day/Month/Year format and it is stored in object format.我有一列日期是日/月/年格式,它以 object 格式存储。 How can I change it to Month/Day/Year format in python?
我怎样才能在python中将其更改为月/日/年格式?
Here is an example: How can I change 13/3/2021 to 3/13/2021?这是一个示例:如何将 13/3/2021 更改为 3/13/2021?
Simple solution is using split:简单的解决方案是使用拆分:
def convert_format1(s: str):
d, m, y = s.split("/")
return "/".join((m, d, y))
Or you can use datetime
module to convert string to datetime object( .strptime
) and vice versa( .strftime
):或者您可以使用
datetime
模块将字符串转换为日期时间对象 ( .strptime
),反之亦然 ( .strftime
):
from datetime import datetime
def convert_format2(s: str):
source_format = "%d/%m/%Y"
destination_format = "%m/%d/%Y"
d = datetime.strptime(s, source_format)
return d.strftime(destination_format)
You can then apply these functions to your dataframe's column.然后,您可以将这些函数应用于数据框的列。
note : AFAIK .strftime()
method adds zero padding to the string representation of day and month.注意:AFAIK
.strftime()
方法将零填充添加到日期和月份的字符串表示中。 If you don't want this behavior you have to strip it manually after that.如果你不想要这种行为,你必须在那之后手动去除它。
note : second function is safer since it checks the dates to be valid as well.注意:第二个 function 更安全,因为它也会检查日期是否有效。
import datetime
t = datetime.date.today()
print(t.month,t.day,t.year,sep="/")
change the value inside the print should let you set yourself改变打印里面的值应该让你自己设置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.