Python字符串转换为日期时间– strptime()

时间:2020-02-23 14:43:32  来源:igfitidea点击:

我们可以使用strptime()函数将字符串转换为datetime。
datetime和time模块中提供了此功能,可分别将字符串解析为datetime和time对象。

Python strptime()

Python strptime()是datetime类中的类方法。
其语法为:

datetime.strptime(date_string, format)

这两个参数都是强制性的,应为字符串。
此函数与strftime()函数正好相反,该函数将datetime对象转换为字符串。

我们在时间模块中也提供了类似的功能,其语法为:

time.strptime(time_string[, format])

这里的函数返回" struct_time"对象。
如果未提供格式字符串,则默认为"%a%b%d%H:%M:%S%Y",它与ctime()函数返回的格式匹配。

如果无法根据提供的格式来解析输入字符串,则将引发" ValueError"。
异常消息提供了有关解析中问题的清晰详细信息。

Python strptime()格式指令

下表包含大多数常用的格式指令。

DirectiveDescriptionExample Output
%aWeekday as locale’s abbreviated name.Sun, Mon, …, Sat (en_US)So, Mo, …, Sa (de_DE)
%AWeekday as locale’s full name.Sunday, Monday, …, Saturday (en_US)Sonntag, Montag, …, Samstag (de_DE)
%wWeekday as a decimal number, where 0 is Sunday and 6 is Saturday.0, 1, 2, 3, 4, 5, 6
%dDay of the month as a zero-padded decimal number.01, 02, …, 31
%bMonth as locale’s abbreviated name.Jan, Feb, …, Dec (en_US)Jan, Feb, …, Dez (de_DE)
%BMonth as locale’s full name.January, February, …, December (en_US)Januar, Februar, …, Dezember (de_DE)
%mMonth as a zero-padded decimal number.01, 02 ... 12
%yYear without century as a zero-padded decimal number.01, 02, ... 99
%YYear with century as a decimal number.0001, 0002, ... , 9999
%HHour (24-hour clock) as a zero-padded decimal number.01, 02, ... , 23
%IHour (12-hour clock) as a zero-padded decimal number.01, 02, ... , 12
%pLocale’s equivalent of either AM or PM.AM, PM (en_US)am, pm (de_DE)
%MMinute as a zero-padded decimal number.01, 02, ... , 59
%SSecond as a zero-padded decimal number.01, 02, ... , 59
%fMicrosecond as a decimal number, zero-padded on the left.000000, 000001, …, 999999Not applicable with time module.
%zUTC offset in the form ±HHMM[SS] (empty string if the object is naive).(empty), +0000, -0400, +1030
%ZTime zone name (empty string if the object is naive).(empty), UTC, IST, CST
%jDay of the year as a zero-padded decimal number.001, 002, …, 366
%UWeek number of the year (Sunday as the first day of the week) as a zero padded decimal number.All days in a new year preceding the first Sunday are considered to be in week 0.00, 01, …, 53
%WWeek number of the year (Monday as the first day of the week) as a decimal number.All days in a new year preceding the first Monday are considered to be in week 0.00, 01, …, 53
%cLocale’s appropriate date and time representation.Tue Aug 16 21:30:00 1988 (en_US)Di 16 Aug 21:30:00 1988 (de_DE)
%xLocale’s appropriate date representation.08/16/88 (None)08/16/1988 (en_US)16.08.1988 (de_DE)
%XLocale’s appropriate time representation.21:30:00 (en_US)21:30:00 (de_DE)
%%A literal '%' character.%

Python strptime()范例

我们来看一些将字符串转换为日期时间和时间对象的strptime()函数的特定示例。

字符串到日期时间

from datetime import datetime

datetime_str = '09/19/18 13:55:26'

datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')

print(type(datetime_object))
print(datetime_object)  # printed in default format

输出:

<class 'datetime.datetime'>
2016-09-19 13:55:26

字符串到日期对象

我们可以使用date()函数和strptime()函数将字符串转换为date对象。

date_str = '09-19-2016'

date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
print(type(date_object))
print(date_object)  # printed in default formatting

输出:

<class 'datetime.date'>
2016-09-19

时间对象的字符串

我们可以使用time()函数和strptime()函数将字符串转换为时间对象。

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

Python时间strptime()示例

我们来看一些使用时间模块strptime()函数的示例。

import time

time_obj = time.strptime(time_str, '%H::%M::%S')
print(type(time_obj))
print(time_obj)

# default formatting - "%a %b %d %H:%M:%S %Y"
print(time.strptime('Wed Sep 19 14:55:02 2016'))

输出:

<class 'time.struct_time'>
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=13, tm_min=55, tm_sec=26, tm_wday=0, tm_yday=1, tm_isdst=-1)
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=19, tm_hour=14, tm_min=55, tm_sec=2, tm_wday=2, tm_yday=262, tm_isdst=-1)

Python strptime()ValueError示例

我们可以使用try-except块来捕获解析异常并执行纠正措施。

datetime_str = '09/19/18 13:55:26'

try:
  datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as ve:
  print('ValueError Raised:', ve)

time_str = '99::55::26'

try:
  time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as e:
  print('ValueError:', e)

输出:

ValueError Raised: unconverted data remains:  13:55:26
ValueError: time data '99::55::26' does not match format '%H::%M::%S'

请注意,ValueError消息清楚地说明了解析异常的根本原因。

Python使用区域设置将字符串转换为日期时间

让我们看一个示例,其中将特定于语言环境的字符串转换为datetime对象。
我们将使用语言环境模块来设置要由python使用的语言环境。

import locale

locale.setlocale(locale.LC_ALL, 'de_DE')
date_str_de_DE = '10-Dezember-2016 Montag'  # de_DE locale
datetime_object = datetime.strptime(date_str_de_DE, '%d-%B-%Y %A')
print(datetime_object)

输出:2016-12-10 00:00:00