**strptime()**方法在datetime和time模块下可用,将字符串解析为datetime和time对象。
Python字符串转换为日期
要在Python中把字符串转换为日期,可以使用strptime()方法。strptime()是datetime类的一个内置方法,用于将日期/时间的字符串表示转换为日期对象。
语法
datetime.strptime(date_string, format)
参数
strptime()函数的两个参数都是必须的,并且应该是一个字符串。strptime()函数与strftime()函数正好相反,后者将日期时间对象转换为字符串。
例子
# app.py
from datetime import datetime
dt_str = '27/10/20 05:23:20'
dt_obj = datetime.strptime(dt_str, '%d/%m/%y %H:%M:%S')
print("The type of the date is now", type(dt_obj))
print("The date is", dt_obj)
输出
The type of the date is now <class 'datetime.datetime'>
The date is 2020-10-27 05:23:20
datetime.strptime()是一个将字符串解析为日期的通用方法。它可以处理各种各样的格式,格式由你给出的格式字符串定义。
使用dateutil将Python字符串转换为日期时间
dateutil可以使用pip软件包管理器从PyPI安装。
要将字符串转换为日期时间,请导入dateutil包并使用解析器模块。
# app.py
from dateutil import parser
dt_str = '27/10/20 05:23:20'
dt_obj = parser.parse(dt_str)
print("The type of the date is now", type(dt_obj))
print("The date is", dt_obj)
输出
The type of the date is now <class 'datetime.datetime'>
The date is 2020-10-27 05:23:20
Python字符串到日期对象
要将Python中的字符串转换为日期对象,可以使用date()函数和strptime()函数。
# app.py
from datetime import datetime
date_str = '10-27-2020'
dto = datetime.strptime(date_str, '%m-%d-%Y').date()
print(type(dto))
print(dto)
输出
<class 'datetime.date'>
2020-10-27
如果字符串参数与格式参数不一致,strptime()函数将无法工作。
用locale将字符串转换为日期时间
要在Python中设置一个locale,在你的Python程序中导入locale包,然后使用locale.setlocale()方法来设置locale。
# app.py
import locale
from datetime import datetime
locale.setlocale(locale.LC_ALL, 'es_ES')
date_str_es = '27-Octubre-2020' # es_ES locale
datetime_object = datetime.strptime(date_str_es, '%d-%B-%Y')
print(datetime_object)
输出
2020-10-27 00:00:00
这就是在Python文章中把字符串转换为日期的方法。
参见
The postHow to Convert Python String to Dateappeared first onAppDividend.