Python模塊datetime使用指南

0. 引入模塊
import datetime
1. 獲取當前時間
now = datetime.datetime.now()
print(now)
today = datetime.date.today()
print('today={today}'.format(today=today))
2. 和字符串的相互轉換
s = now.strftime("%Y-%m-%d %H:%M:%S")
print(s)
s = now.strftime("%Y-%m-%d")
print(s)
date = datetime.datetime.strptime(s, "%Y-%m-%d")
print(date, type(date))
3. 和timestamp相互轉換
timestamp = time.time()
print(timestamp)
dt = datetime.datetime.fromtimestamp(timestamp)
print('dt=%s, type=%s' % (dt, type(dt)))
struct_time = dt.timetuple()
print(struct_time)
timestamp = time.mktime(struct_time)
print(timestamp)
s = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
print(s)
4. 日期之間的計算
start_date = datetime.date(2018, 1, 1)
end_date = datetime.date(2018, 3, 1)
delta_date = datetime.timedelta(days=1)
cur = start_date
while cur <= end_date:
    weekday = cur.isoweekday()
    if 1 <= weekday <= 5:
        print(cur.strftime("%Y-%m-%d"))
    cur += delta_date
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章