Python3知识点详解(二) datetime模块

datetime模块中包含如下类:

date:日期对象,常用的属性有year,month,day;

time:时间对象;

datetime:日期时间对象,常用的属性有hour,minute,second,microsecond;

timedelta:时间间隔,即两个时间点之间的长度;

 

datetime基本操作:

1、获取当前datetime

>>> import datetime

>>> a = datetime.datetime.now()

2018-07-26 14:28:22 249766

 

2、获取当天date:

>>> import datetime

>>> a = datetime.date.today()

2018-07-26

 

3、获取明天/前N天

明天:

>>> import datetime

>>> a = datetime.date.today()+datetime.timedelta(days=1)

>>> print(a)

2018-07-27

 

前三天:

a = datetime.date.today()+datetime.timedelta(days=-3)

or

a = datetime.date.today()-datetime.timedelta(days=3)

 

4、获取当天开始和结束时间(00:00:00 23:59:59)

>>> import datetime

>>> a=datetime.date.today()

>>> b=datetime.time.min

>>> c=datetime.time.max

>>> print(datetime.datetime.combine(a,b))

>>> print(datetime.datetime.combine(a,c))

 

5、获取两个datetime的时间差

>>> (datetime.datetime(2018,7,26,15,34,0)-datetime.datetime.now()).total_seconds()

 

6、获取本周/本月/上月最后一天

本周:

>>> today = datetime.date.today()

>>> today

>>> sunday=today+datetime.timedelta(6-today.weekday())

 

7、Datetime Object/String/timestamp/time tuple关系转换

A、datetime->string

>>> import datetime

>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

'2018-01-12 23:13:08'

B、string->datetime

>>> import datetime

>>> datetime.datetime.strptime("2014-12-31 18:20:10", "%Y-%m-%d %H:%M:%S")

datetime.datetime(2014, 12, 31, 18, 20, 10)

C、datetime->timetuple

>>> import datetime

>>> datetime.datetime.now().timetuple()

time.struct_time(tm_year=2015, tm_mon=1, tm_mday=12, tm_hour=23, tm_min=17, tm_sec=59, tm_wday=0,                            tm_yday=12, tm_isdst=-1)

D、datetime->date

>>> import datetime

>>> datetime.datetime.now().date()

datetime.date(2015, 1, 12)

E、date->datetime

>>> datetime.date.today()

datetime.date(2015, 1, 12)

>>> today = datetime.date.today()

>>>datetime.datetime.combine(today, datetime.time())

datetime.datetime(2015, 1, 12, 0, 0)

>>> datetime.datetime.combine(today, datetime.time.min)

datetime.datetime(2015, 1, 12, 0, 0)

F、datetime->timestamp

>>> now = datetime.datetime.now()

>>> timestamp = time.mktime(now.timetuple())

>>> timestamp 1421077403.0

G、timestamp->datetime

>>> datetime.datetime.fromtimestamp(1421077403.0)

datetime.datetime(2015, 1, 12, 23, 43, 23)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值