經常使用模塊-02datetime模塊

一丶datetime模塊

datetime模塊能夠當作是時間加減的模塊
導入方式:python

import datetime

返回當前時間code

print(datetime.datetime.now())
print(datetime.date.fromtimestamp(time.time()))

2019-08-04
當前時間+3天orm

print(datetime.datetime.now() + datetime.timedelta(3))

2019-03-10 16:22:14.560599
當前時間-3天對象

print(datetime.datetime.now() + datetime.timedelta(-3))

2019-03-04 16:22:14.568473form

2019-03-04 16:22:14.568473class

print(datetime.datetime.now() + datetime.timedelta(hours=3))

2019-03-07 19:22:14.575881import

當前時間+30分鐘date

print(datetime.datetime.now() + datetime.timedelta(minutes=30))

2019-03-07 16:52:14.585432方法

時間替換im

c_time = datetime.datetime.now()
print(c_time.replace(minute=20, hour=5, second=13))

2019-03-07 05:20:13.595493

額外解讀

import datetime

# 自定義日期
res = datetime.date(2019, 7, 15)
print(res)  # 2019-07-15

# 獲取本地時間
# 年月日
now_date = datetime.date.today()
print(now_date)  # 2019-07-01
# 年月日時分秒
now_time = datetime.datetime.today()
print(now_time)  # 2019-07-01 17:46:08.214170

# 不管是年月日,仍是年月日時分秒對象均可以調用如下方法獲取針對性的數據
# 以datetime對象舉例
print(now_time.year)  # 獲取年份2019
print(now_time.month)  # 獲取月份7
print(now_time.day)  # 獲取日1
print(now_time.weekday())  # 獲取星期(weekday星期是0-6) 0表示週一
print(now_time.isoweekday())  # 獲取星期(weekday星期是1-7) 1表示週一

# timedelta對象
# 能夠對時間進行運算操做
import datetime

# 得到本地日期 年月日
tday = datetime.date.today()
# 定義操做時間 day=7 也就是能夠對另外一個時間對象加7天或者減小7點
tdelta = datetime.timedelta(days=7)

# 打印今天的日期
print('今天的日期:{}'.format(tday))  # 2019-07-01
# 打印七天後的日期
print('從今天向後推7天:{}'.format(tday + tdelta))  # 2019-07-08
# 總結:日期對象與timedelta之間的關係
"""
日期對象 = 日期對象 +/- timedelta對象
timedelta對象 = 日期對象 +/- 日期對象

驗證:

"""
# 定義日期對象
now_date1 = datetime.date.today()
# 定義timedelta對象
lta = datetime.timedelta(days=6)
now_date2 = now_date1 + lta  # 日期對象 = 日期對象 +/- timedelta對象
print(type(now_date2))  # <class 'datetime.date'>
lta2 = now_date1 - now_date2  # timedelta對象 = 日期對象 +/- 日期對象
print(type(lta2))  # <class 'datetime.timedelta'>


# 小練習 計算舉例今年過生日還有多少天
birthday = datetime.date(2019, 12, 21)
now_date = datetime.date.today()
days = birthday - now_date
print('生日:{}'.format(birthday))
print('今天的日期:{}'.format(tday))
print('距離生日還有{}天'.format(days))


# 總結年月日時分秒及時區問題
import datetime

dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()  # UTC時間與咱們的北京時間cha ju

print(dt_today)
print(dt_now)
print(dt_utcnow)
相關文章
相關標籤/搜索