1. 程式人生 > >Python3-datetime模塊-日期與時間

Python3-datetime模塊-日期與時間

form pri nal pytho oda min b- date() 模塊

官方文檔

  http://python.usyiyi.cn/translate/python_352/library/datetime.html

代碼示例

技術分享
from datetime import datetime

now = datetime.now()
print("年:%s" % now.year)
print("月:%s" % now.month)
print("日:%s" % now.day)
print("時:%s" % now.hour)
print("分:%s" % now.minute)
print("秒:%s" % now.second)
print("毫秒:%s" % now.microsecond)
print("星期:%s" % now.weekday()) # 星期一到星期日 0-6 print("星期:%s" % now.isoweekday()) # 星期一到星期日 1-7 print("日期:%s" % now.date()) print("時間:%s" % now.time()) print("公裏序數:%s" % now.toordinal()) # 00001年1月1日的公裏序數是1,00001年1月2日的公裏序數是2
1.獲取當前的日期與時間 技術分享
from datetime import datetime

dt = datetime(year=2017, month=6, day=27, hour=16, minute=19, second=52)
print(dt.strftime("%Y-%m-%d %H:%M:%S")) # %Y 以0填充的十進制數字表示的帶有世紀的年份 0001, 0002, ..., 2013, 2014, ..., 9998, 9999 # %y 以0填充的十進制數表示的不帶世紀的年份 00, 01, ..., 99 # %m 以0填充的十進制數字表示的月份 01, 02, 03..., 12 # %d 以0填充的十進制數字表示的月份中的日期 01, 02, 03..., 31 # %H 以0填充的十進制數字表示的小時(24小時制)00, 01, 02, 03...23 # %I 以0填充的十進制數表示的小時(12小時制)01, 02, ..., 12
# %M 以0填充的十進制數字表示的分鐘 00, 01, 02...59 # %S 以0填充的十進制數字表示的秒數 00, 01, 02...59 # %j 以0填充的十進制數字表示的一年中的日期 001,002,...,366 # %% ‘%‘字符的字面值
2.日期時間對象格式化成字符串

  註意: strftime()方法的參數在包含中文時,可能會有錯,有兩個解決辦法,推薦第二種

  技術分享

技術分享
from datetime import datetime
from datetime import timedelta

# 1.給一個日期加上指定的時間
today = datetime.today()
print(today + timedelta(days=1))           # +1 天
print(today + timedelta(days=-1))          # -1 天 => today - timedelta(days=1)
print(today + timedelta(hours=1))          # +1 小時
print(today + timedelta(minutes=120))      # +120 分鐘 => +2小時
print(today + timedelta(seconds=-10))      # -10 秒
print(today + timedelta(weeks=1))          # +1 星期

# 2.兩個日期相減
dt1 = datetime(year=2017, month=6, day=30, hour=13, minute=50)
dt2 = datetime(year=2017, month=6, day=30, hour=16, minute=10)
lag_time = dt2 - dt1
print(lag_time.total_seconds())                  # 相差的時間,單位: 秒
print(lag_time.total_seconds()/60)               # 相差的時間,單位: 分鐘
print(lag_time.total_seconds()/60/60)            # 相差的時間,單位: 小時
3.日期與時間的計算 技術分享
from datetime import datetime

# 使用類方法 datetime.strptime(str, format)
dt = datetime.strptime("2017-6-28 15:56:34", "%Y-%m-%d %H:%M:%S")
print(dt)
print(type(dt))     # 類型: <class ‘datetime.datetime‘>
4.字符串解析成日期時間對象

Python3-datetime模塊-日期與時間