卖逼视频免费看片|狼人就干网中文字慕|成人av影院导航|人妻少妇精品无码专区二区妖婧|亚洲丝袜视频玖玖|一区二区免费中文|日本高清无码一区|国产91无码小说|国产黄片子视频91sese日韩|免费高清无码成人网站入口

Python日期時(shí)間轉(zhuǎn)換:以英文日期轉(zhuǎn)換為例

在數(shù)據(jù)分析和處理中,經(jīng)常需要對(duì)不同格式的日期時(shí)間進(jìn)行轉(zhuǎn)換。本文將以英文日期轉(zhuǎn)換為例,介紹Python datetime模塊的使用方法。1. 獲取英文日期時(shí)間字符串假設(shè)我們從頁(yè)面獲取了一個(gè)英文格式的日期

在數(shù)據(jù)分析和處理中,經(jīng)常需要對(duì)不同格式的日期時(shí)間進(jìn)行轉(zhuǎn)換。本文將以英文日期轉(zhuǎn)換為例,介紹Python datetime模塊的使用方法。

1. 獲取英文日期時(shí)間字符串

假設(shè)我們從頁(yè)面獲取了一個(gè)英文格式的日期時(shí)間字符串:"Mar 09, 2018",希望將其轉(zhuǎn)換成標(biāo)準(zhǔn)的日期時(shí)間格式:"2018-03-09"。

2. 使用datetime模塊轉(zhuǎn)換成datetime對(duì)象

要實(shí)現(xiàn)這個(gè)目標(biāo),首先需要把字符串轉(zhuǎn)換成datetime對(duì)象??梢允褂胐atetime模塊中的strptime方法,該方法接受兩個(gè)參數(shù):第一個(gè)參數(shù)是待轉(zhuǎn)換的字符串,第二個(gè)參數(shù)是字符串對(duì)應(yīng)的日期時(shí)間格式。下面是一個(gè)格式化表格。

| 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對(duì)象的格式為"%b %d, %Y"。

下面是代碼示例:

```python

import datetime

t "Mar 09, 2018"

dt (t, '%b %d, %Y')

```

3. 把datetime對(duì)象轉(zhuǎn)換成字符串

有了datetime對(duì)象后,再把它轉(zhuǎn)換成字符串就容易了??梢允褂胹trftime方法,該方法接受一個(gè)字符串參數(shù),表示待轉(zhuǎn)換成的日期時(shí)間格式。下面的代碼把datetime對(duì)象轉(zhuǎn)換成標(biāo)準(zhǔn)的日期時(shí)間格式:"2018-03-09"。

```python

formatted_date ('%Y-%m-%d')

```

4. 使用一行代碼實(shí)現(xiàn)轉(zhuǎn)換

以上步驟可以用一行代碼實(shí)現(xiàn):

```python

formatted_date str((t, '%b %d, %Y')).split(' ')[0]

```

5. 推薦閱讀官方代碼例子

除了本文介紹的轉(zhuǎn)換方法外,Python datetime模塊還提供了很多其他有用的功能,例如計(jì)算日期時(shí)間差、生成指定日期時(shí)間間隔的時(shí)間序列等等。更多詳情請(qǐng)參閱官方文檔:datetime-objects

標(biāo)簽: