打印与解析日期时间

在 Python 中处理日期和时间

Max Shron

Data Scientist and Author

打印日期时间

# 创建 datetime
dt = datetime(2017, 12, 30, 15, 19, 13)

print(dt.strftime("%Y-%m-%d"))
2017-12-30
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
2017-12-30 15:19:13
在 Python 中处理日期和时间

打印日期时间

print(dt.strftime("%H:%M:%S on %Y/%m/%d/"))
15:19:13 on 2017/12/30
在 Python 中处理日期和时间

ISO 8601 格式

# ISO 8601 格式
print(dt.isoformat())
2017-12-30T15:19:13
在 Python 中处理日期和时间

使用 strptime 解析日期时间

# Import datetime
from datetime import datetime
在 Python 中处理日期和时间

使用 strptime 解析日期时间

# Import datetime
from datetime import datetime

dt = datetime.strptime(
在 Python 中处理日期和时间

使用 strptime 解析日期时间

# Import datetime
from datetime import datetime

dt = datetime.strptime("12/30/2017 15:19:13"
在 Python 中处理日期和时间

使用 strptime 解析日期时间

# Import datetime
from datetime import datetime

dt = datetime.strptime("12/30/2017 15:19:13", 
                       "%m/%d/%Y %H:%M:%S")
在 Python 中处理日期和时间

使用 strptime 解析日期时间

# 我们创建了什么?
print(type(dt))
<class 'datetime.datetime'>
# 打印 datetime 对象
print(dt)
2017-12-30 15:19:13
在 Python 中处理日期和时间

使用 strptime 解析日期时间

# Import datetime
from datetime import datetime

# 错误的格式字符串
dt = datetime.strptime("2017-12-30 15:19:13", "%Y-%m-%d")
ValueError: unconverted data remains:  15:19:13
在 Python 中处理日期和时间

用 Python 解析日期时间

# 一个时间戳
ts = 1514665153.0

# 转为 datetime 并打印 print(datetime.fromtimestamp(ts))
2017-12-30 15:19:13
在 Python 中处理日期和时间

打印与解析日期时间

在 Python 中处理日期和时间

Preparing Video For Download...