Python日期時間轉(zhuǎn)換:以英文日期轉(zhuǎn)換為例
在數(shù)據(jù)分析和處理中,經(jīng)常需要對不同格式的日期時間進行轉(zhuǎn)換。本文將以英文日期轉(zhuǎn)換為例,介紹Python datetime模塊的使用方法。1. 獲取英文日期時間字符串假設(shè)我們從頁面獲取了一個英文格式的日期
在數(shù)據(jù)分析和處理中,經(jīng)常需要對不同格式的日期時間進行轉(zhuǎn)換。本文將以英文日期轉(zhuǎn)換為例,介紹Python datetime模塊的使用方法。
1. 獲取英文日期時間字符串
假設(shè)我們從頁面獲取了一個英文格式的日期時間字符串:"Mar 09, 2018",希望將其轉(zhuǎn)換成標(biāo)準(zhǔn)的日期時間格式:"2018-03-09"。
2. 使用datetime模塊轉(zhuǎn)換成datetime對象
要實現(xiàn)這個目標(biāo),首先需要把字符串轉(zhuǎn)換成datetime對象??梢允褂胐atetime模塊中的strptime方法,該方法接受兩個參數(shù):第一個參數(shù)是待轉(zhuǎn)換的字符串,第二個參數(shù)是字符串對應(yīng)的日期時間格式。下面是一個格式化表格。
| Code | Meaning |
|------|---------|
| %a | Weekday abbreviated name (Sun, Mon, Tue, etc.) |
| %A | Weekday full name (Sunday, Monday, Tuesday, etc.) |
| %b | Month abbreviated name (Jan, Feb, Mar, etc.) |
| %B | Month full name (January, February, March, etc.) |
| %c | Locale’s appropriate date and time representation |
| %d | Day of the month (01 to 31) |
| %H | Hour in 24-hour format (00 to 23) |
| %I | Hour in 12-hour format (01 to 12) |
| %j | Day of the year (001 to 366) |
| %m | Month as a decimal number (01 to 12) |
| %M | Minute (00 to 59) |
| %p | AM or PM |
| %S | Second (00 to 59) |
| %U | Week number of the year (Sunday as the first day of the week) |
| %w | Weekday as a decimal number (0 to 6; Sunday is 0) |
| %W | Week number of the year (Monday as the first day of the week) |
| %x | Locale’s appropriate date representation |
| %X | Locale’s appropriate time representation |
| %y | Year without century (00 to 99) |
| %Y | Year with century |
| %z | UTC offset in the form HHMM or -HHMM |
| %Z | Time zone name (empty string if the object is naive) |
| %% | A literal '%' character |
通過查看上表,可以得知把"Mar 09, 2018"轉(zhuǎn)換成datetime對象的格式為"%b %d, %Y"。
下面是代碼示例:
```python
import datetime
t "Mar 09, 2018"
dt (t, '%b %d, %Y')
```
3. 把datetime對象轉(zhuǎn)換成字符串
有了datetime對象后,再把它轉(zhuǎn)換成字符串就容易了??梢允褂胹trftime方法,該方法接受一個字符串參數(shù),表示待轉(zhuǎn)換成的日期時間格式。下面的代碼把datetime對象轉(zhuǎn)換成標(biāo)準(zhǔn)的日期時間格式:"2018-03-09"。
```python
formatted_date ('%Y-%m-%d')
```
4. 使用一行代碼實現(xiàn)轉(zhuǎn)換
以上步驟可以用一行代碼實現(xiàn):
```python
formatted_date str((t, '%b %d, %Y')).split(' ')[0]
```
5. 推薦閱讀官方代碼例子
除了本文介紹的轉(zhuǎn)換方法外,Python datetime模塊還提供了很多其他有用的功能,例如計算日期時間差、生成指定日期時間間隔的時間序列等等。更多詳情請參閱官方文檔:datetime-objects