Turning dates into strings

Working with Dates and Times in Python

Max Shron

Data Scientist and Author

ISO 8601 format

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']
Working with Dates and Times in Python

ISO 8601 format

# 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']
Working with Dates and Times in Python

Every other format

d.strftime()
Working with Dates and Times in Python

Every other format: 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
Working with Dates and Times in Python

Every other format: strftime

# Format: YYYY/MM/DD
print(d.strftime("%Y/%m/%d"))
2017/01/05
Working with Dates and Times in Python

Turning dates into strings

Working with Dates and Times in Python

Preparing Video For Download...