How to convert csv file data using Python

Asked 2 years ago, Updated 2 years ago, 108 views

In the csv file, the values of the 'Date' column are expressed as 'dd-Jul-yy', but I want to change them all to 'yyy-mm-dd' How do I do this? Python masters, help me

python csv data

2022-09-21 23:11

1 Answers

You can use datetime.

from datetime import *

dateStr = '31-Jul-18'
date = datetime.strptime(dateStr, '%d-%b-%y')
newDateStr = date.strftime('%Y-%m-%d')

print(newDateStr)

The value of the Date column cut and imported in commas can be considered as dateStr. Convert this to a datetime object using datetime.strptime().

Refer to https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior for the %d-%b-%y format used at this time.

This converted datetime object can be converted to a string via datetime.strftime(). %Y-%m-%d is the desired format yyyy-mm-dd.

You can save the time newDateStr converted to a string in CSV.


2022-09-21 23:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.