Python Forum
convert strings of date to datetime exported from CSV
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
convert strings of date to datetime exported from CSV
#1
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!
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Exclamation Date format convert problem for SQL server eotret 5 1,929 Aug-09-2024, 07:19 AM
Last Post: Pedroski55
  Compare current date on calendar with date format file name Fioravanti 1 1,881 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Python date format changes to date & time 1418 4 2,522 Jan-20-2024, 04:45 AM
Last Post: 1418
  Trying to understand strings and lists of strings Konstantin23 2 1,718 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Review my code: convert a HTTP date header to a datetime object stevendaprano 1 4,016 Dec-17-2022, 12:24 AM
Last Post: snippsat
  Convert Date to another format lonesoac0 2 2,373 Mar-17-2022, 11:26 AM
Last Post: DeaD_EyE
  Splitting strings in list of strings jesse68 3 2,544 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Filter dataframe by datetime.date column glidecode 2 9,617 Dec-05-2021, 12:51 AM
Last Post: glidecode
  Date format and past date check function Turtle 5 9,552 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  How to add previous date infront of every unique customer id's invoice date ur_enegmatic 1 2,807 Feb-06-2021, 10:48 PM
Last Post: eddywinch82

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020