将日期转换为字符串

在 Python 中处理日期和时间

Max Shron

Data Scientist and Author

ISO 8601 格式

from datetime import date

# Example date
d = date(2017, 11, 5)

# ISO format: YYYY-MM-DD print(d)
2017-11-05
# Express the date in ISO 8601 format and put it in a list
print( [d.isoformat()] )
['2017-11-05']
在 Python 中处理日期和时间

ISO 8601 格式

# A few dates that computers once had trouble with
some_dates = ['2000-01-01', '1999-12-31']

# Print them in order print(sorted(some_dates))
['1999-12-31', '2000-01-01']
在 Python 中处理日期和时间

其他所有格式

d.strftime()
在 Python 中处理日期和时间

其他格式:strftime

# Example date
d = date(2017, 1, 5)

print(d.strftime("%Y"))
2017
# Format string with more text in it
print(d.strftime("Year is %Y"))
Year is 2017
在 Python 中处理日期和时间

其他格式:strftime

# Format: YYYY/MM/DD
print(d.strftime("%Y/%m/%d"))
2017/01/05
在 Python 中处理日期和时间

将日期转换为字符串

在 Python 中处理日期和时间

Preparing Video For Download...