Python Forum

Full Version: convert strings of date to datetime exported from CSV
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello.
I am using python3 to export some date from a csv file.
I have a csv file full of dates in the form of dd/mm/yyyy
Suppose that I have two strings s1='31/10/2019' and s2='20/09/2019' that I got from the csv file
how can I convert those two strings to datetime objects so that I can subtract them and get the days pass between those two dates
Thank you!
you can use datetime module from standard library
or install and use some of the popular third-party packages that supposedly make it more convenient to work with dates. If it just for subtracting two dates built-in module should do

>>> from datetime import datetime
>>> s1='31/10/2019'
>>> s2='20/09/2019'
>>> d1 = datetime.strptime(s1, '%d/%m/%Y')
>>> d2 = datetime.strptime(s2, '%d/%m/%Y')
>>> date_diff = (d1 - d2).days
>>> date_diff
41