Python的時間處理

第三方模塊 :python-dateutil

安裝方式:pip install python-dateutil

加減時間段實例代碼:

import datetime
from dateutil.relativedelta import relativedelta
 
datetime_now = datetime.datetime.now()
datetime_three_month_ago = datetime_now - relativedelta(days=3)
print datetime_three_month_ago

Python time & datetime & string 相互轉換

import datetime
import time

# 日期時間字符串
st = "2017-11-23 16:10:10"
# 當前日期時間
dt = datetime.datetime.now()
# 當前時間戳
sp = time.time()

# 1.把datetime轉成字符串
def datetime_toString(dt):
    print("1.把datetime轉成字符串: ", dt.strftime("%Y-%m-%d %H:%M:%S"))


# 2.把字符串轉成datetime
def string_toDatetime(st):
    print("2.把字符串轉成datetime: ", datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S"))


# 3.把字符串轉成時間戳形式
def string_toTimestamp(st):
    print("3.把字符串轉成時間戳形式:", time.mktime(time.strptime(st, "%Y-%m-%d %H:%M:%S")))


# 4.把時間戳轉成字符串形式
def timestamp_toString(sp):
    print("4.把時間戳轉成字符串形式: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(sp)))


# 5.把datetime類型轉外時間戳形式
def datetime_toTimestamp(dt):
    print("5.把datetime類型轉外時間戳形式:", time.mktime(dt.timetuple()))


# 1.把datetime轉成字符串
datetime_toString(dt)
# 2.把字符串轉成datetime
string_toDatetime(st)
# 3.把字符串轉成時間戳形式
string_toTimestamp(st)
# 4.把時間戳轉成字符串形式
timestamp_toString(sp)
# 5.把datetime類型轉外時間戳形式
datetime_toTimestamp(dt)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章