python: datetime包,获得当前日期时间
前言
- 前言
- datetime类
- strftime按指定格式输出字符
本篇记录一下,在python中使用datetime包获取当前日期时间的方法。
datetime类datetime
是python内置的一个组件包,datetime
包中有一个datetime
类,还有一个now()
方法用于获取当前的时间的datetime
对象:
import datetime
now = datetime.datetime.now()
print(now) # 2022-03-20 18:32:14.178030
datetime
类有year, month, day, hour, minute, second, microsecond
等成员,比如上面的对象now
:
# now: datetime.datetime(2022, 3, 20, 18, 32, 14, 178030)
print(now.year) # 2022
print(now.month) # 3
print(now.day) # 20
strftime按指定格式输出字符
datetime
类的方法strftime
,按指定格式从datetime
对象返回一个字符串(不会改变对象自身):
s = now.strftime('%y%m%d')
print(s) # '220320'
print(now) # 2022-03-20 18:32:14.178030
# now: datetime.datetime(2022, 3, 20, 18, 32, 14, 178030)
其中,常用的格式表示如下:
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时(0-23)
%M 分钟(00-59)
%S 秒(00-59)