datetime模块

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

  • date 处理年、月、日
  • time 处理时、分、秒和分数
  • datetime 处理日期和时间同时出现的情况
  • timedelta 处理日期和/或时间间隔

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)
  • 用 timedelta 对象来实现 date 的加法:
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
  • combine() 方法把一个date对象和一个time对象合并成一个datetime对象:
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

你可能感兴趣的:(datetime模块)