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

Python中的_strptime()函数实现时间字符串的解析

发布时间:2024-01-10 08:31:48

_strptime()函数是Python中time模块中的一个函数,用于将字符串解析为时间对象。

datetime.strptime(date_string, format)函数接受两个参数: 个参数是一个字符串,表示待解析的时间字符串;第二个参数是一个字符串,表示时间字符串的格式。

以下是对_strptime()函数的具体解释及使用例子:

1. format参数中的格式字符串:

- %Y:4位数的年份

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

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

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

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

- %S:秒数(00-59)

2. 使用例子:

from datetime import datetime

# 将字符串解析为时间对象
date_string = "2021-09-30 16:30:45"
date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(date_object)
# 输出:2021-09-30 16:30:45

# 将字符串解析为日期对象
date_string = "2021-09-30"
date_object = datetime.strptime(date_string, "%Y-%m-%d")
print(date_object)
# 输出:2021-09-30 00:00:00

# 将字符串解析为时间对象,并只获取小时和分钟
time_string = "16:30"
time_object = datetime.strptime(time_string, "%H:%M")
print(time_object)
# 输出:1900-01-01 16:30:00

# 若字符串与格式不匹配,则会抛出ValueError异常
wrong_format_string = "2021-09-30 16:30:45"
wrong_format_object = datetime.strptime(wrong_format_string, "%Y/%m/%d %H:%M:%S")
# 抛出ValueError: time data '2021-09-30 16:30:45' does not match format '%Y/%m/%d %H:%M:%S'

总结:

_strptime()函数可以将时间字符串按照指定的格式解析为时间对象或日期对象。它对于处理时间字符串非常有用,能够提取出特定的时间信息。在使用时要注意字符串的格式和格式字符串参数的匹配关系,否则解析会失败并抛出异常。