python_note
  • Introduction
  • My Python
    • Anaconda
    • argparse
    • datetime
    • json
    • logging
    • numpy
    • open
    • openCC
    • pandas & csv
    • Socket & SocketServer
    • re
    • yaml
    • smtp
    • 物件操作
    • unittest
    • 線程
    • prettytable
    • IO
    • pycurl
    • sys
    • pickle
    • auto-python-to-exe
    • cython
    • nuitka
  • Crawler
    • Urllib & Requests
      • User-agent
      • Percent-Encoding
      • mail code
    • Selenium
    • TCP & UDP
    • 控制字符(control character)
  • Web Development
    • Flask
      • RESTful api
      • Template
      • blueprint
    • Django
      • 環境佈署(windows)
    • 檢查Port
    • Apache
    • 使用者行為
    • jQuery
    • 壓力測試
    • DataTable
    • Bootstrap
    • CSS
    • JavaScript
    • Chart.js
  • Deep Learning
    • Keras 設定
    • RNN
    • LSTM
  • Test
    • T-Test
  • 資料結構
    • Hash
    • 時間複雜度
  • NLP
    • N-gram
    • CKIP
    • 中文轉數字
    • CRF
    • Mutual Information
    • 模糊比對
  • Linebot
    • Heroku
    • 圖文選單
    • channel
  • Linux
    • 常用指令
    • shell script
    • sshfs
    • ssh
    • nodejs & npm
    • debug
  • GCP
    • app engine
    • ssh(gcp)
    • gsutil
    • brabrabra
    • Load Balancer
    • k8s
  • Database
    • mysql
    • elasticsearch
      • Query
      • Backup and Restore
      • elasticdump
      • es2csv
      • ELK
    • mongodb
      • install
      • authentication
      • pymongo
    • sql server
  • go
    • Swarm
  • Docker
    • Kitematic
    • Dockerfile
    • Swarm
  • Git
  • 其他
    • USB軟體保護
    • Windows效能監視器
  • Blockchain
Powered by GitBook
On this page
  • 字串與日期轉換
  • 日期加減
  • 取得當前日期
  • date vs datetime
  • 月份區間處理

Was this helpful?

  1. My Python

datetime

字串與日期轉換

from datetime import date, timedelta, datetime

# 將字串轉換為日期,可比大小,型態為datetime.datetime
date_date = datetime.strptime('2017-10-10','%Y-%m-%d')

# 將datetime.datetime轉換為str
date_str = date_date.strftime('%Y-%m-%d')

日期加減

#python3
from datetime import date, timedelta, datetime

# 將字串轉換為日期,可比大小
date=datetime.strptime('2017-10-10','%Y-%m-%d')

# 昨天
new_date_str = (date.today()-timedelta(1)).strftime('%Y-%m-%d') # 字串型態
new_date = datetime.strptime(new_date_str, '%Y-%m-%d') # 日期型態

# 昨天再往前推十天
old_date_str = (date.today()-timedelta(10)).strftime('%Y-%m-%d')
old_date = datetime.strptime(old_date_str, '%Y-%m-%d')

print('today: ', date.today())
print('new: ', new_date_str)
print('old: ', old_date_str)

delta = int((new_date - old_date).days) 
print('delta: ', delta)

# 用迴圈列出區間所有日期
for i in range(delta+1):
    print(i, new_date - timedelta(i))

輸出

today:  2018-06-28
new:  2018-06-27
old:  2018-06-18
delta:  9
0 2018-06-27 00:00:00
1 2018-06-26 00:00:00
2 2018-06-25 00:00:00
3 2018-06-24 00:00:00
4 2018-06-23 00:00:00
5 2018-06-22 00:00:00
6 2018-06-21 00:00:00
7 2018-06-20 00:00:00
8 2018-06-19 00:00:00
9 2018-06-18 00:00:00

取得當前日期

#取得當前時間,可指定格式
import time
print(time.strftime("%Y-%m-%d_%H:%M:%S"))
# 2018-10-12_13:43:48 type=str

from datetime import date
print(date.today())
# 2018-10-12 type=datetime.date

date vs datetime

不同type無法比較

from datetime import date, timedelta, datetime

# 將字串轉換為日期,可比大小
date_date = datetime.strptime('2017-10-10', '%Y-%m-%d')

if date_date > date.today():
    print('ok')
# error:can't compare datetime.datetime to datetime.date

月份區間處理

from datetime import datetime, date, timedelta
import calendar

# 取得該月的天數(n),並從該日往後n天
def get_month_range(start_input=None, mode='str'):
    if mode != 'str' and mode != 'datetime':
        print('mode must be str or datetime')
        sys.exit()

    if start_input is None:
        start_date = date.today().replace(day=1)  # 變成1號
    else:
        start_date = datetime.strptime(start_input, '%Y-%m-%d')
        start_date = start_date.replace(day=1)

    _, days_in_month = calendar.monthrange(start_date.year, start_date.month)  # 該月的天數
    end_date = start_date + timedelta(days=days_in_month - 1)  # 從一號推算出最後一號

    start_date = start_date.strftime('%Y-%m-%d')
    end_date = end_date.strftime('%Y-%m-%d')
    if mode == 'datetime':
        start_date = datetime.strptime(start_date, '%Y-%m-%d')
        end_date = datetime.strptime(end_date, '%Y-%m-%d')

    return [start_date, end_date]

# 判斷兩個時間區間之間是否有交集
def match_month_range(old_date, new_date, month_start, month_end):
    match = False
    date_delta = (new_date - old_date).days
    for i in range(0, date_delta + 1):
        date_now = old_date + timedelta(days=i)
        # print(date_now)
        if month_start <= date_now <= month_end:
            # print('ok', date_now)
            match = True
            break
    return match
# 取得月或日
start_date.month
PreviousargparseNextjson

Last updated 5 years ago

Was this helpful?

參考來源:

參考連結:

http://blog.webgolds.com/view/6
http://wiki.alarmchang.com/index.php?title=使用Python_做日期的加減(相差幾天)(datetime\