title: How to format datetime values in csv file/column in python?
body: <p>I have a csv file which contains several lines and in particular, column sending time. I wish to change the timedate formats <strong>from DD/MM/YYYYHH:MM:SS.DDDD</strong> <strong>to</strong> <strong>YYYYMMDD-HH:MM:SS</strong> for all values in column SendingTime.</p>
  <p><strong>CSV Example:</strong></p>
  <pre><code>MsgType,CompID,SendingTime    
  AR ,SDF,16/08/2021 09:13:13.09934
  </code></pre>
  <p>I have found a code snippet on StackOverflow, and I'm trying the following to change the datetime format, however, to no avail and the below error. Any help would be most appreciated?</p>
  <pre><code>import csv
  import re
  from datetime import datetime
   
  lines = []
  # open file as read-only
  with open('datetimeissue.csv', &quot;r&quot;, 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&quot;\d+\/\d+\/\d+ \d+\:\d+\:\d+&quot;, string):
                  datetimeobject = datetime.strptime(string, '%d/%m/%Y %h:%m:%s')
                  new_string = datetimeobject.strftime('%Y-%m-%d-%h:%m:%s')
                  row[i] = new_string
                  print(&quot;Replaced&quot;, string, &quot;with&quot;, 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('mynewoverwritten.csv', &quot;w&quot;, newline='') as data:
      writer = csv.writer(data)
      writer.writerows(lines)
  </code></pre>
  <p><strong>Error Extract</strong></p>
  <pre><code>Traceback (most recent call last):
    File &quot;time.py&quot;, line 14, in &lt;module&gt;
      datetimeobject = datetime.strptime(string, '%d/%m/%Y %h:%m:%s')
    File &quot;/usr/lib64/python3.6/_strptime.py&quot;, line 565, in _strptime_datetime
      tt, fraction = _strptime(data_string, format)
    File &quot;/usr/lib64/python3.6/_strptime.py&quot;, line 354, in _strptime
      (bad_directive, format)) from None
  ValueError: 'h' is a bad directive in format '%d/%m/%Y %h:%m:%s'
  </code></pre>