[Python]strptime将文本String解析成时间日期格式

2021-05-15 900点热度 0人点赞 0条评论

strptime可以根据特定的格式化的时间格式,将文本解析成datetime类型。

datetime格式化的日期时间格式,可以参考:https://blog.terrynow.com/2021/05/13/python-strftime-format-datetime-force-with-locale-string/

from datetime import datetime

date_string1 = "2021-05-15"
date_string2 = "2021-05-15 18:08"

print("日期1string =", date_string1)
print("type of date_string =", type(date_string1))

date_object1 = datetime.strptime(date_string1, "%Y-%m-%d")
date_object2 = datetime.strptime(date_string2, "%Y-%m-%d %H:%M")

print("日期1 =", date_object1)
print("日期2 =", date_object2)
print("type of date_object =", type(date_object1))

以上代码运行结果:

日期1string = 2021-05-15
type of date_string = <class 'str'>
日期1 = 2021-05-15 00:00:00
日期2 = 2021-05-15 18:08:00
type of date_object = <class 'datetime.datetime'>

格式化符号详解

Python的格式化符号和Java的有点不一样,整理如下:

Directive Meaning Example
%a 本地简化星期名称 四,Sun, Mon, ...
%A 本地完整星期名称 星期四,Sunday, Monday, ...
%w 星期(0-6),星期天为星期的开始 0, 1, ..., 6
%d 两位数表示的月内中的一天(01-31) 01, 02, ..., 31
%-d 月内中的一天(1-31) 1, 2, ..., 30
%b 本地简化的月份名称 Jan, Feb, ..., Dec
%B 本地完整的月份名称 五月,January, February, ...
%m 两位数表示的月份 01, 02, ..., 12
%-m 数字表示的月份 1, 2, ..., 12
%y 两位数的年份表示(00-99) 00, 01, ..., 99
%-y 数字表示的年份 0, 1, ..., 99
%Y 四位数的年份表示(000-9999) 2013, 2019 etc.
%H 两位数表示的24小时制小时数(0-23) 00, 01, ..., 23
%-H 数字表示的24小时的小时数 0, 1, ..., 23
%I 两位数表示的12小时制小时数(01-12) 01, 02, ..., 12
%-I 12小时制小时数(1-12) 1, 2, ... 12
%p 本地A.M.或P.M.的等价符 上午,AM, PM
%M 两位数表示的分钟数(00-59) 00, 01, ..., 59
%-M 数字表示的分钟数 0, 1, ..., 59
%S 两位数表示的秒(00-59) 00, 01, ..., 59
%-S 数字表示的秒 0, 1, ..., 59
%f 六位数表示的微秒 000000 - 999999
%z 时差+0000, -0400 +0000, -0400
%Z 当前时区的名称
%j 3位数表示的年内的一天(001-366) 001, 002, ..., 366
%-j 数字表示的年内的一天(1-366) 1, 2, ..., 366
%U 一年中的星期数(00-53)星期天为星期的开始 00, 01, ..., 53
%W 一年中的星期数(00-53)星期一为星期的开始 00, 01, ..., 53
%c 本地相应的日期表示和时间表示 Mon Sep 30 07:06:05 2013
%x 本地相应的日期表示 09/30/13,2021/05/13
%X 本地相应的时间表示 07:06:05
%% %号本身 %

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论