Working with Dates and Times in Python
Max Shron
Data Scientist and Author
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']
# 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']
d.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
# Format: YYYY/MM/DD
print(d.strftime("%Y/%m/%d"))
2017/01/05
Working with Dates and Times in Python