日期格式转换——显式方式
来看一下上个练习中的一条日期数据。
- Sale A: 4000,日期为 14/02/2018
我们使用 datetime 库识别了日 d、月 m、年 y,这有助于在不同日期格式的数据集中定位数据。不过,如果我们想把日期格式转换成某个指定的格式,该怎么做?
在本练习中,您将把 Sale A 的日期从 14/02/2018 转换为与 Sale B 相同的日期格式(即 14 February 2018)。
借助 Python 内置函数,我们可以轻松完成。请记住,拆分字符串可以使用 .split() 方法。
本练习的输入是 Sale A 的日期时间。
本练习是课程的一部分
Python 金融预测
练习说明
- 创建变量
dt,其中包含您要转换为新格式的日期的字符串表示(即 Sale A)。 - 创建月份字典
mm,用于指定每个月对应的数字,格式为{'number':'month name'}。 - 使用字符
/拆分字符串dt,并将结果分别赋给day、month和year变量。 - 通过拼接字符串并使用字典中对应的月份名称,将结果按新格式打印出来。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Set the variable for the datetime to convert
dt = '____'
# Create the dictionary for the month values
mm = {'01': '____', '____': 'February', '____': '____'}
# Split the dt string into the different parts
____, ____, year = dt.split('____')
# Print the concatenated date string
print(____ + ' ' + ____[____] + ' ' + ____)