Python / datetime
===
###### tags: `Python`
###### tags: `Python`, `datetime`, `year`, `month`, `day`, `hour`, `minute`, `second`, `millisecond`, `week_of_month`, `week_of_year`, `day_of_week`
<br>
[TOC]
<br>
## doc
### [時間格式代碼](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)
- [Java Calendar使用](https://www.itread01.com/content/1513833628.html)
<br>
## strftime
- [Format a datetime into a string with milliseconds](https://stackoverflow.com/questions/7588511/)
```python
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'
```
Or shorter:
```python
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]
'2022-09-24 10:18:32.926'
```
<br>
## week_of_month
- [python - Week number of the month](https://stackoverflow.com/questions/3806473)
```python=
def week_of_month(dt):
""" Returns the week of the month for the specified date.
"""
first_day = dt.replace(day=1)
dom = dt.day
adjusted_dom = dom + first_day.weekday()
return int(ceil(adjusted_dom/7.0))
```
## week_of_year
- [Python date calculating with year and week of year is incorrect](https://stackoverflow.com/questions/52843238)
```python=
import datetime
datetime.datetime(2021, 1, 30, 15, 0, 0).strftime('%V')
```
## day_of_week
- [Getting Day Of Year For A Given Date In Python](https://www.mytecbits.com/internet/python/day-of-year)
```python=
datetime.date(2021, 3, 30).timetuple().tm_yday
```
- timetutple
```
time.struct_time(
tm_year=2021, <-- year
tm_mon=3, <-- month
tm_mday=30, <-- day_of_month
tm_hour=0, <-- hour
tm_min=0, <-- minute
tm_sec=0, <-- second
tm_wday=1, <-- day_of_week, 0-6, base=Monday
tm_yday=89, <-- day_of_week, 1-365, base=1
tm_isdst=-1 <-- 夏令時標誌
)
```
- [【C】解釋struct tm中的tm_isdst欄位](https://www.796t.com/post/OTc4azY=.html)
<br>
## timestamp
```python
output_filename = datetime.now().strftime(
'%Y%m%d-%H%M%S') + '.mp4'
```
<br>
## timedelta
- [Cleanest and most Pythonic way to get tomorrow's date?](https://stackoverflow.com/questions/1506901/)
```
datetime.date.today() + datetime.timedelta(days=1) should do the trick
```
<br>
## 參考資料
- [Python datetime](https://www.programiz.com/python-programming/datetime)
<br>
## 討論
### elapsed_time vs duration
- ### Question
在衡量 benchmark 指標方面,elapsed_time 和 duration 哪個比較恰當?
i.e., end_time - start_time
- ### ChatGPT-4o
在衡量 benchmark 指標時,`elapsed_time` 和 `duration` 這兩個術語通常可以互換使用,但它們在特定情境下可能有細微的差異。
- **`elapsed_time`**:這個詞強調的是從開始到結束的總經過時間,通常用來描述整個過程的持續時間。當你測量的是一個事件、過程或操作的完整經過時間時,`elapsed_time` 是比較常見且直觀的選擇。
- **`duration`**:這個詞則更側重於描述某個特定事件或狀態的持續時間,也就是說,在某段時間內某個狀態的持續時間。`duration` 可能更適合用來表示在測量過程中某個特定階段的時間。
在 `end_time` - `start_time` 這樣的計算中,兩者都可以適用,但 **`elapsed_time`** 可能更為恰當,因為它直接表達了從開始到結束的總時間,與 benchmark 的概念更為契合。
因此,在這種情況下,我會建議使用 `elapsed_time` 作為指標名稱。
<br>
### 'datetime.timedelta' object has no attribute 'strftime'
- ### Question
使用 python datetime 處理 elapsed time
遇到:
`AttributeError: 'datetime.timedelta' object has no attribute 'strftime'`
- ### ChatGPT-4o
這個錯誤的原因是因為 datetime.timedelta 物件沒有 strftime 方法。strftime 是 datetime 物件的方法,用來格式化日期和時間,而 timedelta 物件則代表兩個 datetime 物件之間的差異(即經過的時間),並不提供格式化的方法。
要處理 timedelta 物件並以合適的格式表示經過時間,你可以手動提取天數、秒數,然後進行格式化。以下是如何做到這一點的範例:
```python=
from datetime import datetime, timedelta
# 假設這是 start_time 和 end_time
start_time = datetime(2023, 8, 12, 14, 0, 0)
end_time = datetime(2023, 8, 13, 16, 30, 45)
# 計算 elapsed_time
elapsed_time = end_time - start_time
# 提取天數、秒數、並將其轉換為小時、分鐘和秒
days = elapsed_time.days
seconds = elapsed_time.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
# 格式化輸出
elapsed_time_str = f"{days} days, {hours:02}:{minutes:02}:{seconds:02}"
print(elapsed_time_str)
```
這段代碼將輸出:
```
1 days, 02:30:45
```
如果你只對小時、分鐘和秒有興趣,忽略天數,可以這樣:
```python=
total_seconds = int(elapsed_time.total_seconds())
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
# 格式化輸出
elapsed_time_str = f"{hours:02}:{minutes:02}:{seconds:02}"
print(elapsed_time_str)
```
這將輸出:
```
26:30:45
```
這種方法可以幫助你將 timedelta 物件轉換為所需的時間格式。