datetime模块

2016-08-11  本文已影响13人  乐小Pi孩_VoV

标准的 datetime 模块,它定义了 4 个主要的对象,每个对象都有很多方法:

1.创建一个 date 对象,以及它的属性

from datetime important date
>>> a=date(2016,8,11)   
>>> a.year
2016
>>> a.month
8
>>> a.day
11
>>> a.isoformat()            #isoformat()方法,? - ? - ? 
'2016-08-11'
>>> now=date.today()         #today()获取今天的日期
>>> now
datetime.date(2016, 8, 11)
from datetime import timedelta, date

one_day = timedelta(days=1)
now = date.today()
print(now)                   # 2016-08-11
tomorrow = now + one_day
print(tomorrow)          # 2016-08-12
a = now + 17 * one_day
print(a)                      # 016-08-28

2.创建一个 time 对象,以及它的属性:

from datetime import time

noon = time(12, 30, 59)
print(noon)  # 12:30:59
print(noon.hour)  # 12
print(noon.minute)  # 30
print(noon.second)  # 59

3.创建一个 datetime 对象,以及它的属性:

from datetime import datetime

some_day = datetime(2016, 1, 2, 3, 4, 5, 6)
print(some_day)  # 2016-01-02 03:04:05.000006
print(some_day.isoformat())  # 2016-01-02T03:04:05.000006

now = datetime.now()
print(now)  # 2016-08-11 08:13:54.714372
# now.month,now.day,.....now.microsecond
from datetime import datetime, date, time

noon = time(12)  # 12:00:00
this_day = date.today()  # 2016-08-11
noon_today = datetime.combine(this_day, noon)
print(noon_today)  # 2016-08-11 12:00:00
上一篇 下一篇

猜你喜欢

热点阅读