Currently I'm capturing dates from a csv file, but the date field can come in any format.
I want to transform this dates to only %Y-%m-%d date format. But with strptime does not work.
For example:
Csv Dates ----> Transformation
2020/06/23 06:00
---> 2020-06-23
23/04/2020 05:00
---> 2020-04-23
11/4/2020 10:00
---> 2020-04-11
2022/1/24 11:00
---> 2022-01-24
Code:
fecha_csv = row[7]
fecha_csv = datetime.strptime(fecha_csv, '%Y-%m-%d %H:%M:%S')
fecha_csv = fecha_csv.date()
CodePudding user response:
This is assuming the format of dates that you have given in your example. to format further dates this may need to be modified depending on the date given.
the problem you are having possibly is that you aren't converting it into a proper datetime object so that you can change it to the date format that you would like.
you can change the date format with time into just the date with a couple of methods. one is to just do string manipulation if the date is always formatted the same like the examples shown or you could convert it to datetime objects like the following.
fecha_csv = row[7]
if len(fecha_csv.split('/')[0]) > 2: # year is first
datetime.strptime(fecha_csv, '%Y/%m/%d %H:%M').strftime("%Y-%m-%d")
else: # year is last
datetime.strptime(fecha_csv, '%d/%m/%Y %H:%M').strftime("%Y-%m-%d")
A problem with your current code is that it was formatted to read dates in as 2020-06-23 06:00:00 when it should only be formatted to read in as 2020/06/23 06:00
CodePudding user response:
Or try using a date parser -
from dateutil.parser import parse fetch_csv = parse(fetch_csv).date()