Learning DateTime module in Python

Python commands for the standard datetime module in Python

 

Convert string to time and vice versa: 

Commands

  • from datetime import datetime
  • .strptime() - converts string to time format
    Usage datetime.strptime(variable, format)
    such as: date_dt = datetime.strptime(date,'%m/%d/%Y' )
  • .strftime() - converts time to a string format
    Usage datetime.strftime(variable, format)
    such as: datetime.strftime(variable, '%m/%d/%Y')
  • Alternative on converting from time to string, use the output standard ISO-8601
    such as datetime.isoformat(variable)

Working with datetime components

Important to make sure that you present data in the viewers native timezone.

  • We can use the different pieces of time, for example in a dictionary we can use datetime.month() as the key
  • datetime.now() gives the time on the local computer
  • datetime.utcnow() gives the time on the local computer but in utc time
  • In order to work with timezones effectively, use the pytz library
    Such as: from pytz import timezone 
    We can then use the timezone constructor and pass it a name such as: CT = timezone('US/Central')
  • chicago_usa_tz = timezone('US/Central') - gives the timezone of Chicago
  • Making the item "aware" for Chicago 
    Such as: 
    chicago_dt = orig_dt.replace(tzinfo=chicago_usa_tz) 
  • Convert the chicago time to NY time
    Such as: ny_dt = chicago_dt.astimezone(ny_usa_tz)
  • The important part above is that chicago is being replaced when it's being aware of chicago, so we create an aware datapoint. Then we use our new chicago datetimeobject and pass it as the time in New York. The usage of this is to show different datapoints across timezones, for example in train departure times. 

Adding and subtracting time

Useful in comparing month to month and other datetimes. 
A common usecase is to get data from 30, 60 or 90 days back in time. 

  1. from datetime import timedelta
  2. timedelta is used to represent an amount of change in time
  3. Set timedelta to a number of days
    Such as: flashback = timedelta(days=90)  


Libraries to make datetime easier

 

  • import pendulum
  • Timezone hopping with pendulum
  • .in_timezone()
  • pendulum.now() - gives the current time in the specified timezone
  • .in_words() - humanizes the datetime object into readable format