資料使用上會有需要將時間相關的資料轉換成特定格式。
不論是從str轉datetime或是datetime轉換成其他格式。
分享時間格式轉換上很常用到的兩個韓式strptime和strftime
時間格式
時間格式全部都是使用一個%,加上一個字母來代表,其中大小寫會有不同的意義,這裡舉一寫比較常使用到的引述作為舉例。
| 引述 | 代表 | 例子 |
|---|---|---|
| %a | 星期簡寫 | Mon |
| %A | 星期 | Monday |
| %b | 月份 | 簡寫Jan |
| %B | 月份 | January |
| %d | 日期 | 31 |
| %H | 小時(24小時制) | 23 |
| %I | 小時(12小時制) | 12 |
| %p | AM 或 PM | AM |
| %P | am 或 pm | am |
| %m | 月份(十進制) | 01 |
| %M | 分鐘 | 59 |
| %S | 秒數 | 59 |
| %y | 年份(沒有世紀) | 99 |
| %Y | 年份(有世紀) | 1999 |
字串轉時間格式
請參考下方程式碼:
import time
timeString = "Mon, 31 Jan 2022 00:00:00 GMT"
print(type(timeString)) #<class 'str'>
struct_time = time.strptime(timeString, "%a, %d %b %Y %H:%M:%S GMT")
print(type(struct_time)) #<class 'time.struct_time'>
new_timeString = time.strftime("%Y-%b-%d", struct_time)
print(new_timeString) #2022-Jan-31
print(type(new_timeString)) #<class 'str'>
時間格式轉成指定格式字串
請參考下方程式碼:
from datetime import datetime
now = datetime.now()
print(type(now)) #<class 'datetime.datetime'>
print(now) #印出2022-12-15 14:16:33.724054
print(now.strftime("%Y-%b-%d")) #出2022-Dec-15
#上面這個函式跟datetime無關
延伸推薦