python時間處理 time,datetime,arrow


內置time

import time

# 時間戳
# print(time.time()) 
# 時間戳轉換系統時間 2018-04-04 11:00:55 # ctime = time.localtime(time.time()) # print(time.strftime('%Y-%m-%d %H:%M:%S',ctime)) # 睡1秒 (秒單位) # print(time.sleep(1)) # 輸出當前系統時間 # x = time.localtime() # t = time.strftime('%Y-%m-%d %H:%M:%S', x) # 按格式輸入當前時間 , x = 元組 # print(t) # 2018-02-06 16:37:30
# 轉換時間數組
# dt = "2016-05-05 20:28:54"
# dt2 = time.strptime(dt,"%Y-%m-%d %H:%M:%S")
# time.struct_time(tm_year=2016, tm_mon=5, tm_mday=5, tm_hour=20, tm_min=28, tm_sec=54, tm_wday=3, tm_yday=126, tm_isdst=-1)
# 在轉換日期時間
# dt3 = time.strftime("%Y-%m-%d %H:%M:%S",dt2)
# print(dt3)

  

內置datetime 可以做日期加減

# 對time模塊的封裝
import datetime

# %Y-%m-%d %H:%M:%S
# 年 月  日 時 分 秒
# 當前日期
# print('當前日期:', datetime.datetime.now())  # 當前日期: 2018-04-04 11:04:46.090568
# 日期相加 (3天后的日期)
# print(datetime.datetime.now() + datetime.timedelta(3))  # 2018-04-07 11:04:46.090568
# 日期相減 3天前
# print(datetime.datetime.now() + datetime.timedelta(-3))
# 小時相加 , -3減
# print(datetime.datetime.now() + datetime.timedelta(hours=3))

# 時間替換
# c_time = datetime.datetime.now()
# print(c_time.replace(year=2019))  # 2019-04-04 11:29:47.653526

# 數據庫查詢返回的時間類型,轉換位 時分
# t = datetime.datetime(2018, 4, 4, 10, 48, 59, 793000).strftime('%H:%M')  # 10:48
# print(t)


# t_str = '2012-03-05 16:26:23'
# 將字符串轉換為datetime 日期 string => datetime
# d = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')
# 這樣就可以進行加減了
# print(d + datetime.timedelta(-3))

# 2個日期比較
# d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
# d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
# delta = d1 - d2
# print(delta.days)

Arrow 庫

安裝   pip install arrow

import arrow

# 獲取當前時間
now2 = arrow.utcnow()  # 時間戳 timestamp
# print(now2.timestamp)
#
now = arrow.now()
print(now.timestamp)  # 時間戳
# t = now.format('YYYY-MM-DD HH:mm')  # 2018-04-04 09:39
# print('當前時間',t)
# mm = start.format('HH:mm')  # 09:48
# 當前時間加1分鍾
# n = now.shift(minutes=1)
# print('當前時間加1分鍾',n.format('YYYY-MM-DD HH:mm'))
# 當前時間加1小時
# n = now.shift(hours=1)
# print('當前時間加1小時',n.format('YYYY-MM-DD HH:mm'))
# n = now.shift(months=1)
# print('當前時間加1月',n.format('YYYY-MM-DD HH:mm'))
# n = now.shift(years=1)
# print('當前時間加1年',n.format('YYYY-MM-DD HH:mm'))
# n = now.shift(days=1)
# print('當前時間加1天',n.format('YYYY-MM-DD HH:mm'))
# n = now.shift(days=-1)
# print('當前時間加-1天',n.format('YYYY-MM-DD HH:mm'))
# n = now.shift(weeks=1)
# print('當前時間加1周',n.format('YYYY-MM-DD HH:mm'))

# ---------------- 轉換arrow對象
# 字符串轉換arrow對象
# strarr = arrow.get("2017-01-20 11:30", "YYYY-MM-DD HH:mm")
# year = strarr.format('YYYY')
# print(year)
# 時間戳轉換arrow對象
# sjc = arrow.get("1485937858.659424").format("YYYY-MM-DD")
# print(sjc)
# 直接生產一個Arrow對象
# aw = arrow.Arrow(2017, 2, 1)
# print(aw.format('YYYY:MM-DD HH:mm'))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM