Python 時間模塊datetime常用操作


測試的時間為:2018-10-31 晚7點左右

獲取當前datetime

# 獲取當前時間
now = datetime.datetime.now()
print now               # 2018-10-31 19:53:05.507000
print now.day           # 31        幾號
print now.month         # 10        幾月
print now.year          # 2018      哪一年
print now.hour          # 19        時
print now.minute        # 53        分
print now.second        # 5         秒
print now.microsecond   # 507000    毫秒

獲取當前date

# 獲取當前日期
date_today = datetime.date.today()
print date_today        # 2018-10-31    日期
print date_today.day    # 31            天
print date_today.month  # 10            月
print date_today.year   # 2018          年

獲取明天/前n天

# 獲取明天/前N天
today = datetime.date.today()
# 明天
tomorrow = today + datetime.timedelta(days=1)
# 前3天
pre_n_day = today - datetime.timedelta(days=3)
print today          # 2018-10-31
print tomorrow       # 2018-11-01
print pre_n_day      # 2018-10-28

獲取兩個datetime的時間差

# 獲取時間差
pre_time = datetime.datetime(2018, 9, 10, 6, 0, 0)  # 年月日時分秒
now = datetime.datetime.now()

total_days = (now - pre_time).days          # 相差的天數
total_seconds = (pre_time - now).seconds    # 相差的秒數

print now - pre_time        # 51 days, 14:18:12.272000
print total_days            # 51
print total_seconds         # 34907

獲取本周/本月/上月最后一天

 

# 獲取本周最后一天日期
today = datetime.date.today()
sunday = today + datetime.timedelta(6 - today.weekday())
print sunday                # 2018-11-04

# 獲取本月最后一天
today = datetime.date.today()
_, month_total_days = calendar.monthrange(today.year, today.month)
month_last_day = datetime.date(today.year, today.month, month_total_days)
print month_last_day        # 2018-10-31

# 獲取上個月的最后一天
today = datetime.date.today()
first = datetime.date(day=1, month=today.month, year=today.year)
pre_month_last_day = first - datetime.timedelta(days=1)
print pre_month_last_day    # 2018-09-30

 

參考資料:

timedelta 相關

 https://www.cnblogs.com/zknublx/p/6017094.html

calendar 相關

https://www.cnblogs.com/keqipu/p/7228502.html

其他

https://blog.csdn.net/u010541307/article/details/53162227

https://www.cnblogs.com/sunshine-blog/p/8477893.html

 


免責聲明!

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



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