介绍
Python的datetime
和time
模块都包含了一个strptime()
类方法,用于将字符串转换为对象。
在本文中,您将使用strptime()
将字符串转换为datetime
和struct_time()
对象。
使用DigitalOcean App Platform从GitHub部署您的Python应用程序。让DigitalOcean专注于扩展您的应用。
使用datetime.strptime()
将字符串转换为datetime
对象
datetime.strptime()
方法的语法为:
datetime.strptime(date_string, format)
datetime.strptime()
方法返回一个与date_string匹配的datetime
对象。这两个参数都是必需的,且必须是字符串。
有关在datetime.strptime()
中使用的格式指令的详细信息,请参阅Python文档中的strftime()
和strptime()
格式代码。
将字符串转换为datetime.datetime()
对象示例
以下示例将日期和时间字符串转换为datetime.datetime()
对象,并打印生成对象的类名和值:
from datetime import datetime
datetime_str = '09/19/22 13:55:26'
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')
print(type(datetime_object))
print(datetime_object) # 默认格式打印
输出为:
<class 'datetime.datetime'>
2022-09-19 13:55:26
将字符串转换为datetime.date()
对象示例
以下示例将日期字符串转换为datetime.date()
对象,并打印生成对象的类类型和值:
from datetime import datetime
date_str = '09-19-2022'
date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
print(type(date_object))
print(date_object) # 默认格式打印
输出为:
<class 'datetime.date'>
2022-09-19
将字符串转换为datetime.time()
对象示例
以下示例将时间字符串转换为datetime.time()
对象,并打印生成对象的类类型和值:
from datetime import datetime
time_str = '13::55::26'
time_object = datetime.strptime(time_str, '%H::%M::%S').time()
print(type(time_object))
print(time_object)
输出为:
<class 'datetime.time'>
13:55:26
使用区域设置将字符串转换为datetime.datetime()
对象的示例
以下示例将德国区域设置日期字符串转换为datetime.datetime()
对象,并打印生成对象的类类型和值:
from datetime import datetime
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
date_str_de_DE = '16-Dezember-2022 Freitag' # de_DE 区域设置
datetime_object = datetime.strptime(date_str_de_DE, '%d-%B-%Y %A')
print(type(datetime_object))
print(datetime_object)
输出为:
<class 'datetime.datetime'>
2022-12-16 00:00:00
请注意,生成的对象不包括输入字符串中的星期几名称,因为datetime.datetime()
对象仅将星期几包含为十进制数。
使用time.strptime()
将字符串转换为struct_time()
对象
time.strptime()
方法的语法是:
time.strptime(time_string[, format])
time.strptime()
方法返回一个匹配由 time_string 解析的 format 的 time.struct_time()
对象。 time_string 是必需的,两个参数都必须是字符串。 如果未提供 format,则默认为:
'%a %b %d %H:%M:%S %Y'
这对应于 ctime()
函数返回的格式。
格式指令对于 time.strptime()
和 time.strftime()
是相同的。 在 Python 文档中了解有关 time
模块的 格式指令 的更多信息。
提供格式的示例:将字符串转换为 struct_time()
对象
以下示例通过提供 format 参数将时间字符串转换为 time.struct_time()
对象,并打印结果对象的值:
import time
time_str = '11::33::54'
time_obj = time.strptime(time_str, '%H::%M::%S')
print("A time.struct_time object that uses the format provided:")
print(time_obj)
输出为:
A time.struct_time object that uses the format provided:
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1,
tm_hour=11, tm_min=33, tm_sec=54, tm_wday=0, tm_yday=1,
tm_isdst=-1)
如输出所示,当将字符串转换为 time.struct_time()
对象时,strptime()
方法对于在 format 参数中未定义的任何格式指令都使用占位符值。
使用默认格式示例将字符串转换为struct_time()
对象
如果在将时间字符串转换为time.struct_time()
对象时没有提供格式参数,则会使用默认格式,如果输入字符串与默认格式不完全匹配,则会发生错误:
'%a %b %d %H:%M:%S %Y'
以下示例将一个时间字符串转换为没有提供格式参数的time.struct_time()
对象,并打印结果对象的值:
import time
# 默认格式 - "%a %b %d %H:%M:%S %Y"
time_str_default = 'Mon Dec 12 14:55:02 2022'
time_obj_default = time.strptime(time_str_default)
print("A time.struct_time object that uses the default format:")
print(time_obj_default)
输出为:
A time.struct_time object that uses the default format:
time.struct_time(tm_year=2022, tm_mon=12, tm_mday=12,
tm_hour=14, tm_min=55, tm_sec=2, tm_wday=0, tm_yday=346,
tm_isdst=-1)
如输出所示,当将字符串转换为time.struct_time()
对象时,strptime()
方法对于任何未在格式参数中定义的格式指令或者如果没有提供格式参数,则使用占位值。
解决strptime()
错误
如果使用提供的格式无法解析输入字符串,则会引发`ValueError`。 您可以使用`try`块来测试解析错误,以及`except`块来打印结果。 当您使用`strptime()`方法时,获取的`ValueError`消息清楚地解释了解析错误的根本原因。 以下示例演示了一些常见的错误,例如额外的数据和格式不匹配:
from datetime import datetime
import time
datetime_str = '09/19/18 13:55:26'
try:
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as ve1:
print('ValueError 1:', ve1)
time_str = '99::55::26'
try:
time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as ve2:
print('ValueError 2:', ve2)
输出为:
ValueError 1: unconverted data remains: 13:55:26
ValueError 2: time data '99::55::26' does not match format '%H::%M::%S'
结论
在本教程中,您使用Python将日期和时间字符串转换为`datetime`和`time`对象。 继续学习更多有关Python教程。
Source:
https://www.digitalocean.com/community/tutorials/python-string-to-datetime-strptime