Printing and parsing datetimes

Working with Dates and Times in Python

Max Shron

Data Scientist and Author

Printing datetimes

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

Printing datetimes

print(dt.strftime("%H:%M:%S on %Y/%m/%d/"))
15:19:13 on 2017/12/30
Working with Dates and Times in Python

ISO 8601 Format

# ISO 8601 format
print(dt.isoformat())
2017-12-30T15:19:13
Working with Dates and Times in Python

Parsing datetimes with strptime

# Import datetime
from datetime import datetime
Working with Dates and Times in Python

Parsing datetimes with strptime

# Import datetime
from datetime import datetime

dt = datetime.strptime(
Working with Dates and Times in Python

Parsing datetimes with strptime

# Import datetime
from datetime import datetime

dt = datetime.strptime("12/30/2017 15:19:13"
Working with Dates and Times in Python

Parsing datetimes with strptime

# Import datetime
from datetime import datetime

dt = datetime.strptime("12/30/2017 15:19:13", 
                       "%m/%d/%Y %H:%M:%S")
Working with Dates and Times in Python

Parsing datetimes with strptime

# What did we make?
print(type(dt))
<class 'datetime.datetime'>
# Print out datetime object
print(dt)
2017-12-30 15:19:13
Working with Dates and Times in Python

Parsing datetimes with strptime

# Import datetime
from datetime import datetime

# Incorrect format string
dt = datetime.strptime("2017-12-30 15:19:13", "%Y-%m-%d")
ValueError: unconverted data remains:  15:19:13
Working with Dates and Times in Python

Parsing datetimes with Python

# A timestamp
ts = 1514665153.0

# Convert to datetime and print print(datetime.fromtimestamp(ts))
2017-12-30 15:19:13
Working with Dates and Times in Python

Printing and parsing datetimes

Working with Dates and Times in Python

Preparing Video For Download...