12 01 Dates and Calendars - HannaAA17/Data-Scientist-With-Python-datacamp GitHub Wiki

Dates in Python

Creating date objects

# Import date
from datetime import date

# Create dates
two_hurricanes_dates = [date(2016, 10, 7), date(2017, 6, 21)]

Attributes of a date

  • year: two_hurricanes_dates[0].year
  • month: two_hurricanes_dates[0].month
  • day: two_hurricanes_dates[0].day
  • weekday: two_hurricanes_dates[0].weekday()
    • 0 = Monday

Math with Dates

  • min,max: min(two_hurricanes_dates): 2016-10-07
  • timedelta object

Subtracting dates

# Import date
from datetime import date

# Create a date object for May 9th, 2007
start = date(2007, 5, 9)

# Create a date object for December 13th, 2007
end = date(2007, 12, 13)

# Subtract the two dates and print the number of days
print((end - start).days) # the (end-start) is a timedelta object
from datetime import timedelta

# Create a 29 day timedelta
td = timedelta(days=29)
print(d1 + td)

Putting a list of dates in order

  • sorted()
# Put the dates in order
dates_ordered = sorted(dates_scrambled)

Turning dates into Strings

ISO 8601 format

  • YYYY-MM-DD
    • print(d)
    • print([d.isoformat()])

Other format

  • d.strftime()
# Assign the earliest date to first_date
first_date = min(florida_hurricane_dates)

# Convert to ISO and US formats
iso = "Our earliest hurricane date: " + first_date.isoformat()
us = "Our earliest hurricane date: " + first_date.strftime("%m/%d/%Y")

print("ISO: " + iso) #  ISO: Our earliest hurricane date: 1950-08-31
print("US: " + us) # US: Our earliest hurricane date: 08/31/1950
  • Print the date in the format 'YYYY-MM'
    • print(andrew.strftime('%Y-%m'))
  • Print the date in the format 'MONTH (YYYY)'
    • print(andrew.strftime('%B (%Y)'))
  • Print the date in the format 'YYYY-DDD'
    • print(andrew.strftime('%Y-%j'))