> For the complete documentation index, see [llms.txt](https://dinoin.gitbook.io/shi-py-bu-shi-pi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dinoin.gitbook.io/shi-py-bu-shi-pi/datetime.md).

# datetime

時間日期

{% code title="datetime to string" %}

```python
from datetime import datetime
now = datetime.now()
s = datetime.strftime(now,'%Y-%m-%d %H:%M:%S')
```

{% endcode %}

{% code title="string to datetime" %}

```python
from datetime import datetime
print datetime.strptime('2019-01-01','%Y-%m-%d')
```

{% endcode %}

## 時間格式判斷

```
try:
    time_format = "%Y-%m-%d %H:%M:%S"
    datetime.datetime.strptime(time, time_format)
except ValueError:
    raise ValueError(f"Incorrect time format! Should be {time_format}")
```

> 格式參考：<https://www.cnblogs.com/dplearning/p/5737966.html>

## 計算

### 加減n日

```python
from datetime import datetime, timedelta
time = datetime.now()

# 減1日
time = time - timedelta(days=1)

# 減1年
time = time - timedelta(days=365)
```

{% hint style="info" %}
這個方法沒有「年月」的處理，需要換算成天或是改用別的。
{% endhint %}

> 參考：<https://blog.csdn.net/CSDN__YX/article/details/120050559>

### 耗時

```python
time_monitor = time.time()
print('耗時:', time.time() - time_monitor)
```
