日付フォーマットの変換 - 基本
ヨーロッパの販売エリアAとオーストラリアの販売エリアBでは、日付の表記が異なります。
- Sale A: 2018年02月14日に4000
- Sale B: 2018年3月2日に3000
販売期間を集計・比較するには、同じ日付フォーマットにそろえる必要があります。これは datetime ライブラリと datetime.strptime(date_string, format) メソッドを使えば簡単に行えます。主なディレクティブは次のとおりです。
| Directive | Meaning | Example |
|---|---|---|
| %d | 月内の日(ゼロ埋めの10進数) | 01, 02, …, 31 |
| %b | ロケールの省略形の月名 | Jan, Feb, …, Dec |
| %B | ロケールの完全な月名 | January, …, December |
| %m | 月(ゼロ埋めの10進数) | 01, 02, …, 12 |
| %y | 世紀なしの年(ゼロ埋めの10進数) | 00, 01, …, 99 |
| %Y | 世紀を含む年(10進数) | 1970, 1988, 2001, 2013 |
この演習はコースの一部です
Pythonで学ぶファイナンシャル・フォーキャスティング
演習の手順
datetimeライブラリをインポートします。- 各販売の日付を、日-月-年の標準化フォーマットに変換する
dt_objectを作成します。 - 結果をそれぞれ出力して比較します
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Import the datetime python library
from ____ import ____
# Create a dt_object to convert the first date and print the month result
dt_object1 = datetime.strptime('14/02/2018', '____')
print(____)
# Create a dt_object to convert the second date and print the month result
dt_object2 = datetime.strptime('2 March 2018', '____')
print(____)