开始使用免费开始使用

转换日期格式——基础

欧洲的销售区域 A 和澳大利亚的销售区域 B 使用了不同的日期格式。

  • 销售 A: 4000,日期为 14/02/2018
  • 销售 B: 3000,日期为 2 March 2018

如果我们要汇总或比较销售期间,就需要将日期转换为相同的格式。我们可以使用 datetime 库和 datetime.strptime(date_string, format) 方法轻松完成,使用以下指令:

Directive Meaning Example
%d 月中的某一天(零填充的十进制数) 01, 02, …, 31
%b 本地化的月份缩写 Jan, Feb, …, Dec
%B 本地化的月份全称 January, …, December
%m 月份(零填充的十进制数) 01, 02, …, 12
%y 两位年份(零填充的十进制数) 00, 01, …, 99
%Y 四位年份(含世纪的十进制数) 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(____)
编辑并运行代码