# datetime

## 字串與日期轉換

```python
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')
```

## 日期加減

```python
#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
```

### 取得當前日期

```python
#取得當前時間，可指定格式
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
```

參考來源：\
<http://blog.webgolds.com/view/6>

## date vs datetime

不同type無法比較

```python
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
```

參考連結：\
[http://wiki.alarmchang.com/index.php?title=使用Python\_做日期的加減(相差幾天)(datetime\\](http://wiki.alarmchang.com/index.php?title=使用Python_做日期的加減%28相差幾天%29%28datetime%29\\)

### 月份區間處理

```python
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
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://stb11816.gitbook.io/python_note/web/datetime.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
