Python datetime 常用方法統整

Posted on  Sep 8, 2016  in  Python 程式設計 - 初階  by  Amo Chen  ‐ 1 min read

Python 內建有不少時間相關的操作函數,本篇將如何取得日期區間記錄成 Python recipes ,以供方便使用。

這些方法主要使用 timedelta 進行時間加減、 calendar 取得月份天數以及其他 datetime 模組所提供之函數組合而成。

import calendar

from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

# 取得今天日期
today = date.today() # datetime.date(2014, 6, 2)

# 取得今天 0 時 0 分
datetime.combine(today, time.min) # dateime.date(2014, 6, 2, 0, 0)

# 取得今天 23 時 59 分 59 秒
datetime.combine(today, time.max) # datetime.datetime(2014, 6, 2, 23, 59, 59, 999999)

# 取得本月天數
days = calendar.monthrange(today.year, today.month)[1] # 30

# 取得本月最後 1 天日期
date(today.year, today.month, days) # datetime.date(2014, 6, 30)

# 取得本月 1 號
date(today.year, today.month, 1) #  datetime.date(2014, 6, 1)

# 取得上月第 1 天與最後 1 天
def previous_month_range():
    today = date.today()

    # number of days in previous month
    last_dt = today - timedelta(days=today.day)
    return (
        date(last_dt.year, last_dt.month, 1),
        date(last_dt.year, last_dt.month, last_dt.day)
    )

# 取得去年的今天
today - timedelta(days=365) # datetime.date(2013, 6, 2)

# 取得本週第 1 天與最後 1 天(Mon, Sun)
def current_week_range():
    today = date.today()
    y, m, d, dow = today.year, today.month, today.day, today.weekday()
    add_timedelta = timedelta(days=6-dow)
    sub_timedelta = timedelta(days=dow)
    return (today - sub_timedelta, today + add_timedelta)

參考資料:

https://docs.python.org/2/library/datetime.html

https://docs.python.org/2/library/calendar.html

對抗久坐職業傷害

研究指出每天增加 2 小時坐著的時間,會增加大腸癌、心臟疾病、肺癌的風險,也造成肩頸、腰背疼痛等常見問題。

然而對抗這些問題,卻只需要工作時定期休息跟伸展身體即可!

你想輕鬆改變現狀嗎?試試看我們的 PomodoRoll 番茄鐘吧! PomodoRoll 番茄鐘會根據你所設定的專注時間,定期建議你 1 項辦公族適用的伸展運動,幫助你打敗久坐所帶來的傷害!

追蹤新知

看完這篇文章了嗎?還意猶未盡的話,追蹤粉絲專頁吧!

我們每天至少分享 1 篇文章/新聞或者實用的軟體/工具,讓你輕鬆增廣見聞提升專業能力!如果你喜歡我們的文章,或是想了解更多特定主題的教學,歡迎到我們的粉絲專頁按讚、留言讓我們知道。你的鼓勵,是我們的原力!

贊助我們的創作

看完這篇文章了嗎? 休息一下,喝杯咖啡吧!

如果你覺得 MyApollo 有讓你獲得實用的資訊,希望能看到更多的技術分享,邀請你贊助我們一杯咖啡,讓我們有更多的動力與精力繼續提供高品質的文章,感謝你的支持!