Python字符串转换为日期时间– strptime()「建议收藏」

Python字符串转换为日期时间– strptime()「建议收藏」Wecanconvertastringtodatetimeusingstrptime()function.Thisfunctionisavailableindatetimeandtimemodulestoparseastringtodatetimeandtimeobjectsrespectively.我们可以使用strptime()函数将字…

大家好,又见面了,我是你们的朋友全栈君。

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

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

Python strptime() (Python strptime())

Python strptime() is a class method in datetime class. Its syntax is:

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

datetime.strptime(date_string, format)

Both the arguments are mandatory and should be string. This function is exactly opposite of strftime() function, which converts datetime object to a string.

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

We have the similar function available in time module too, where its syntax is:

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

time.strptime(time_string[, format])

Here the function returns struct_time object. If format string is not provided, it defaults to “%a %b %d %H:%M:%S %Y” which matches the formatting returned by ctime() function.

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

If the input string cannot be parsed according to the provided format, then ValueError is raised. The exception message provides clear details about the issue in parsing.

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

Python strptime()格式指令 (Python strptime() format directives)

Following table contains most of the commonly used format directives.

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

Directive Description Example Output
%a Weekday as locale’s abbreviated name. Sun, Mon, …, Sat (en_US)
So, Mo, …, Sa (de_DE)
%A Weekday as locale’s full name. Sunday, Monday, …, Saturday (en_US)
Sonntag, Montag, …, Samstag (de_DE)
%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 0, 1, 2, 3, 4, 5, 6
%d Day of the month as a zero-padded decimal number. 01, 02, …, 31
%b Month as locale’s abbreviated name. Jan, Feb, …, Dec (en_US)
Jan, Feb, …, Dez (de_DE)
%B Month as locale’s full name. January, February, …, December (en_US)
Januar, Februar, …, Dezember (de_DE)
%m Month as a zero-padded decimal number. 01, 02 … 12
%y Year without century as a zero-padded decimal number. 01, 02, … 99
%Y Year with century as a decimal number. 0001, 0002, … , 9999
%H Hour (24-hour clock) as a zero-padded decimal number. 01, 02, … , 23
%I Hour (12-hour clock) as a zero-padded decimal number. 01, 02, … , 12
%p Locale’s equivalent of either AM or PM. AM, PM (en_US)
am, pm (de_DE)
%M Minute as a zero-padded decimal number. 01, 02, … , 59
%S Second as a zero-padded decimal number. 01, 02, … , 59
%f Microsecond as a decimal number, zero-padded on the left. 000000, 000001, …, 999999
Not applicable with time module.
%z UTC offset in the form ±HHMM[SS] (empty string if the object is naive). (empty), +0000, -0400, +1030
%Z Time zone name (empty string if the object is naive). (empty), UTC, IST, CST
%j Day of the year as a zero-padded decimal number. 001, 002, …, 366
%U Week 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
%W Week 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
%c Locale’s appropriate date and time representation. Tue Aug 16 21:30:00 1988 (en_US)
Di 16 Aug 21:30:00 1988 (de_DE)
%x Locale’s appropriate date representation. 08/16/88 (None)
08/16/1988 (en_US)
16.08.1988 (de_DE)
%X Locale’s appropriate time representation. 21:30:00 (en_US)
21:30:00 (de_DE)
%% A literal ‘%’ character. %
指示 描述 示例输出
%一个 工作日为语言环境的缩写名称。 周日,周一,…,周六(en_US)
因此,Mo,…,Sa(de_DE)
%一个 工作日为语言环境的全名。 周日,周一,…,周六(zh_CN)
桑塔格,蒙塔格,…,萨姆斯塔格(de_DE)
%w 以十进制数表示的工作日,其中0是星期日,6是星期六。 0、1、2、3、4、5、6
%d 月份中的一天,以零填充的十进制数字表示。 01,02,…,31
%b 月作为语言环境的缩写名称。 一月,二月,…,十二月(en_US)
一月,二月,…,德兹(de_DE)
%B 月作为语言环境的全名。 一月,二月,…,十二月(zh_CN)
Januar,Februar,…,Dezember(de_DE)
%m 以零填充的十进制数字表示的月份。 01,02…12
%y 无世纪的年份,为零填充的十进制数字。 01,02,…99
%Y 以世纪作为十进制数字的年份。 0001、0002,…,9999
%H 小时(24小时制),为补零的十进制数字。 01,02,…,23
%一世 小时(12小时制),为零填充的十进制数字。 01,02,…,12
%p 相当于AM或PM的语言环境。 上午,下午(en_US)
上午,下午(de_DE)
%M 分钟,为零填充的十进制数字。 01,02,…,59
%S 第二个为零填充的十进制数。 01,02,…,59
%F 微秒,十进制数,在左侧补零。 000000,000001,…,999999
不适用于时间模块。
%z UTC偏移量,格式为±HHMM [SS](如果对象是天真对象,则为空字符串)。 (空),+ 0000,-0400,+ 1030
%Z 时区名称(如果对象是天真对象,则为空字符串)。 (空),UTC,IST,CST
%j 一年中的一天,为零填充的十进制数字。 001,002,…,366
%U 一年中的周号(星期日为一周的第一天),以零填充的十进制数表示。
新年中第一个星期日之前的所有天均视为第0周。
00,01,…,53
%W 一年中的星期数(星期一为一周的第一天),以十进制数表示。
第一个星期一之前的新的一年中的所有天均视为在第0周。
00,01,…,53
%C 语言环境的适当日期和时间表示。 星期二八月16 21:30:00 1988(zh_CN)
Di 16 Aug 21:30:00 1988(de_DE)
%X 语言环境的适当日期表示形式。 88年8月16日(无)
1988年8月16日(zh_CN)
1988年8月16日(de_DE)
%X 语言环境的适当时间表示形式。 21:30:00(zh_CN)
21:30:00(de_DE)
%% 文字“%”字符。

Python strptime()示例 (Python strptime() examples)

Let’s look into some specific examples of strptime() function to convert string to datetime and time objects.

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

字符串到日期时间 (String to datetime)

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

Output:

输出:

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

字符串到日期对象 (String to date object)

We can use date() function alongwith strptime() function to convert string to date object.

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

date_str = '09-19-2018'

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

Output:

输出:

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

时间对象的字符串 (String to time object)

We can use time() function alongwith strptime() function to convert string to time object.

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

time_str = '13::55::26'
time_object = datetime.strptime(time_str, '%H::%M::%S').time()
print(type(time_object))
print(time_object)

Output:

输出:

<class 'datetime.time'>
13:55:26

Python时间strptime()示例 (Python time strptime() example)

Let’s see some examples of using time module strptime() function.

我们来看一些使用时间模块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 2018'))

Output:

输出:

<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=2018, 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示例 (Python strptime() ValueError Example)

We can use try-except block to catch parsing exception and perform corrective actions.

我们可以使用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)

Output:

输出:

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

Notice that the ValueError message clearly explains the root cause of the parsing exception.

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

Python使用区域设置将字符串转换为日期时间 (Python Convert String to Datetime with locale)

Let’s look at an example where a locale-specific string will be converted to datetime object. We will use locale module to set the locale to be used by python.

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

import locale

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

Output: 2018-12-10 00:00:00

输出: 2018-12-10 00:00:00

GitHub Repository.
GitHub存储库中检出完整的python脚本和更多Python示例。

References: datetime strptime(), time strptime()

参考: datetime strptime()时间strptime()

翻译自: https://www.journaldev.com/23365/python-string-to-datetime-strptime

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/137316.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • caffe中常用层: BatchNorm层详解

    caffe中常用层: BatchNorm层详解Batchnorm原理详解前言:Batchnorm是深度网络中经常用到的加速神经网络训练,加速收敛速度及稳定性的算法,可以说是目前深度网络必不可少的一部分。 本文旨在用通俗易懂的语言,对深度学习的常用算法–batchnorm的原理及其代码实现做一个详细的解读。本文主要包括以下几个部分。Batchnorm主要解决的问题Batchnorm原理解读Batchnorm的优点Batchnorm的源码解读第一…

    2022年5月2日
    54
  • 【通俗易懂】关系模式范式分解教程 3NF与BCNF口诀!小白也能看懂「建议收藏」

    本来是为了复习数据库期末考试,结果找了一圈都没有发现比较好的解释,通过查阅资料和总结,为大家提供通俗易懂的解法,一听就会!并且配有速记口诀!介是你没有玩过的船新版本包含最小依赖集求法候选码求法在模式分解之前,首先对于1NF,2NF,3NF,BCNF做一个简明扼要的介绍。1NF是指数据库表的每一列都是不可分割的基本数据项,即实体中的某个属性不能有多个值或者不能有重复的属性。2NF要求属性…

    2022年4月8日
    86
  • uniapp 真机调试_app调试

    uniapp 真机调试_app调试一:华为手机实时调试APP代码基座流程1.打开手机的开发者模式,允许USB调试,手机操作流程,进入设置-关于手机,长按版本号(开启开发模式),然后按图操作,下拉屏幕发行已连接USB调试,手机端就暂时不用再操作了2.电脑安装360手机助手,这个软件打开浏览器或者用360软件助手下载就好了,它是HBuildX和手机连接的桥梁3.HBuildX操作运行之后就可以在控制台查看进展,会自动在手机安装APK调试基座(用于调试的APK,APK就是安卓APP的安装包).

    2025年9月18日
    6
  • ArcGIS 9.3 下载(包含ArcGIS Desktop、ArcGIS Engine、ArcGIS Server、ArcSDE、workstation)

    ArcGIS 9.3 下载(包含ArcGIS Desktop、ArcGIS Engine、ArcGIS Server、ArcSDE、workstation)ArcGIS9.3下载(包含ArcGISDesktop、ArcGISEngine、ArcGISServer、ArcSDE、workstation)

    2022年7月3日
    34
  • 如何遍历ArrayList集合,并安全删除其中的元素[通俗易懂]

    如何遍历ArrayList集合,并安全删除其中的元素[通俗易懂]如何遍历ArrayList集合,并安全删除其中的元素?1、遍历ArrayList集合有三种方式(1)for循环(2)增强for循环,也就是foreach(3)迭代器iterator2、普通for循环遍历删除元素,list集合的大小会变小,而索引也会发生改变,所以利用ffor循环遍历删除元素会漏调某些元素。例如我for循环遍历删除第一个元素,接着按照…

    2022年7月22日
    16
  • htmlimg图片加载失败_js针对图片加载失败的处理方法分析

    htmlimg图片加载失败_js针对图片加载失败的处理方法分析本文实例讲述了js针对图片加载失败的处理方法。分享给大家供大家参考,具体如下:在项目中不可避免会用到图片,尤其是列表,有时候图片会加载失败;这样就会显示一个很难看的坏图片缩略图;下面介绍两种方法,解决这个问题:1、如果在你的项目中有引入jQuery插件,你可以使用error([[data],fn])这个函数;$(“img”).error(function(){//当图片加载失败时,你要进行的操作/…

    2022年5月5日
    409

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号