Pythondatetime模块中datetime类的使用
主要记录下datetime类的一些用法,在碰到时间相关的运算时有个积累。
timedelta对象表示两个不同的date或者time的持续时间,类似于一个时间间隔。
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
>>> now = datetime.now()
>>> now
datetime.datetime(2017, 6, 25, 20, 53, 40, 36492)
>>> day = timedelta(days=3)
>>> now + day
datetime.datetime(2017, 6, 28, 20, 53, 40, 36492)
>>> days = timedelta(days=365)
>>> now + days
datetime.datetime(2018, 6, 25, 20, 53, 40, 36492)
>>>
>>> days = timedelta(year=1)
Traceback (most recent call last):
File "", line 1, in
TypeError: 'year' is an invalid keyword argument for this function
>>> days = timedelta(years=1)
Traceback (most recent call last):
File "", line 1, in
TypeError: 'years' is an invalid keyword argument for this function
>>>
>>> now = datetime.now()
>>> now1 = datetime.now()+ timedelta(days=3)
>>> intervaldays = now1-now
>>> intervaldays
datetime.timedelta(3, 14, 538899)
>>> intervaldays.days
3
>>> intervaldays.seconds
14
>>> intervaldays.microseconds
538899
>>> now1 > now
True
>>> datetime.weekday(now)
6
>>> datetime.isoweekday(now)
7
>>>
>>> now.day
25
>>> now.year
2017
>>> now.minute
0
>>> now.second
43
>>> now.month
6
>>> now.hour
21
>>>
combine函数可以将date和time对象合并起来
>>> d = date(2005, 7, 14)
>>> t = time(12, 30)
>>> datetime.combine(d, t)
datetime.datetime(2005, 7, 14, 12, 30)
这些方法在一般的使用当中基本已经够了,以后用到其他函数场景时,再记录。