How can I change date format in csv in Python 3
Suppose you have a date x
:
x = "2017-07-01T15:55Z"
You can convert it into a datetime.datetime
with your formate %Y-%m-%dT%H:%MZ
:
from datetime import datetime
d = datetime.strptime(x, '%Y-%m-%dT%H:%MZ')
Then format it:
d.strftime("%m/%d/%Y")
You'll get:
'07/01/2017'
The complete code is:
from datetime import datetime
x = "2017-07-01T15:55Z"
x = datetime.strptime(x, '%Y-%m-%dT%H:%MZ').strftime("%m/%d/%Y")
======= EDIT =======
For your follow up question:
you need to change row
after formatting ts
:
ts = row[17]
ts = datetime.strptime(ts, '%Y-%m-%dT%H:%MZ').strftime("%m/%d/%Y")
if ts != "":
row[17] = ts # this is what you miss
writer.writerow(row)
Change date formats in csv with Python 3
import csv
import re
from datetime import datetime
lines = []
# open file as read-only
with open('partner_new_testteam.csv', "r", newline='') as data:
reader = csv.reader(data)
# go over all of its rows, and the row's items and change
# items that match the date format
for row in reader:
for i, string in enumerate(row):
if re.match(r"\d+\/\d+\/\d+", string):
datetimeobject = datetime.strptime(string, '%d/%m/%Y')
new_string = datetimeobject.strftime('%Y-%m-%d')
row[i] = new_string
print("Replaced", string, "with", new_string)
# save edited, and originally correct ones to new list
new_row = row
lines.append(new_row)
# write new rows by overwriting original file
with open('partner_new_testteam.csv', "w", newline='') as data:
writer = csv.writer(data)
writer.writerows(lines)
Your current code does not actually change anything. You never replaced anything and you didn't open the file with write access.
You also should not use try:
like it is an if
. The regex matches x/x/x, where x is any amount of numbers.
Dealing with different date formats in python
Try it one way, and if it doesn't work, try it the other way.
try:
df['Appointment Date'] = pd.to_datetime(df['Appointment Date'], format="%d/%m/%Y/%H:%M:%S").dt.strftime("%d/%m/%Y")
except WhateverDateParseException:
df['Appointment Date'] = pd.to_datetime(df['Appointment Date'], format="%Y/%m/%d/%H:%M:%S").dt.strftime("%d/%m/%Y")
Of course, instead of WhateverDateParseException
use the actual exception that is raised in your code.
Edit: fixed missing "%S"
Related Topics
Running an Excel Macro Via Python
How to Create String With Line Breaks in Python
Selenium Python Send_Key Error: List Object Has No Attribute
How to Handle Multiple Keys for a Dictionary in Python
Why Is This Going Out of Range
Pandas.To_Sql Replace Old Data With New Data Based on 'Unique Id'
Changing File Permission in Python
Using Opencv to Overlay Transparent Image Onto Another Image
Visual Studio Code Pylint: Unable to Import 'Protorpc'
Plotly: Plot Multiple Figures as Subplots
Text Pre-Processing + Python + Csv:Removing Special Characters from a Column of a Csv
Convert SQL Result to List Python
Python Regex - How to Get Positions and Values of Matches
Pandas Convert Columns to Percentages of the Totals
Python - How to Extract Elements from an Array Based on an Array of Indices
Scheduling Python Script to Run Every Hour Accurately
Add One Month to a Given Date (Rounded Day After) With Python