下面是一个示例代码,用于比较美国日期格式(月/日/年)和另一个日期格式(年-月-日):
import datetime
# 美国日期格式(月/日/年)
us_date_string = "12/31/2022"
us_date = datetime.datetime.strptime(us_date_string, "%m/%d/%Y")
us_date_formatted = us_date.strftime("%Y-%m-%d")
print("美国日期格式:", us_date_formatted)
# 另一个日期格式(年-月-日)
other_date_string = "2022-12-31"
other_date = datetime.datetime.strptime(other_date_string, "%Y-%m-%d")
other_date_formatted = other_date.strftime("%m/%d/%Y")
print("另一个日期格式:", other_date_formatted)
输出结果为:
美国日期格式: 2022-12-31
另一个日期格式: 12/31/2022
通过使用datetime
模块的strptime
函数,我们可以将字符串解析为日期对象。然后,可以使用strftime
函数将日期对象格式化为所需的日期格式。在上面的示例中,我们将美国日期格式的日期字符串转换为另一个日期格式,并将另一个日期格式的日期字符串转换为美国日期格式。
上一篇:比较语句和条件语句哪个更快。