欢迎访问宙启技术站
智能推送

在Python中如何使用strftime()函数来对日期时间格式进行转换?

发布时间:2023-09-11 09:32:55

在Python中,strftime()函数用于将日期时间格式转换为字符串形式。它是一个datetime对象的成员函数,通过提供格式代码作为参数,可以根据自定义的格式将日期时间转换为指定的字符串形式。

下面是一些常见的格式代码:

- %Y:4位数的年份(例如:2022)

- %m:2位数的月份(01到12)

- %d:2位数的日期(01到31)

- %H:24小时制的小时(00到23)

- %M:分钟数(00到59)

- %S:秒数(00到59)

- %a:星期的简写形式(Mon到Sun)

- %A:星期的完整形式(Monday到Sunday)

- %b:月份的简写形式(Jan到Dec)

- %B:月份的完整形式(January到December)

下面是使用strftime()函数进行日期时间转换的示例:

import datetime

# 获取当前日期时间
now = datetime.datetime.now()

# 将日期时间转换为标准格式
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)  # 输出:2022-01-01 12:34:56

# 将日期时间转换为自定义格式
formatted = now.strftime("%Y年%m月%d日 %H:%M:%S")
print(formatted)  # 输出:2022年01月01日 12:34:56

# 获取当前星期的简写形式
day = now.strftime("%a")
print(day)  # 输出:Sat

# 获取当前星期的完整形式
day = now.strftime("%A")
print(day)  # 输出:Saturday

# 获取当前月份的简写形式
month = now.strftime("%b")
print(month)  # 输出:Jan

# 获取当前月份的完整形式
month = now.strftime("%B")
print(month)  # 输出:January

需要注意的是,strftime()函数只能用于将日期时间格式转换为字符串形式。如果要将字符串转换为日期时间格式,可以使用strptime()函数。

总结起来,strftime()函数是Python中对日期时间格式进行转换的一个非常有用的工具。通过指定格式代码,可以将日期时间转换为自定义的字符串形式。这对于在日志记录、数据处理等方面非常有用。