How to Get Year, Month, and Day as Integers from an ISO 8601 Formatted Date String in Python 3 with dateutil

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

I’m currently working with the Plaid Banking API and need to convert the ISO 8601 formatted date strings returned by the API into easy to work with integers. While I considered writing my own code to handle this, after a quick Google search I found that this is quite easy to do in Python using the dateutil module. So far I’ve only run this code in the repl.it web based programming environment, but I believe this module can be easily installed with the pip package manager by running something like:

$ pip install python-dateutil

The code snippet below mostly comes from a blog post on CodeYarns.com titled How to convert datetime to and from ISO 8601 string, but I did add the parts which I needed specifically (year, month, day):

# REFERENCE: https://bit.ly/2xLIh6I
import dateutil.parser
# Datestring in ISO 8601 format
datetime_str = "2019-01-23T06:17:59.273519"
# Convert to datetime object
some_datetime_obj = dateutil.parser.parse(datetime_str)
# Get Year, Month, and Day as integers
print(some_datetime_obj.year)
print(some_datetime_obj.month)
print(some_datetime_obj.day)
 

topherPedersen