-1

I'm trying to extract a date from a string and change the date format from yyyy-mm-dd to yyyy/mm/dd. Somehow I got it wrong.

I read through the links below to help me get there, but need a quick hand.

import re
import datetime

str = "2017/09/15 07:11:00"

x = re.match( r'([^\s]+)',str)
new_x = datetime.datetime.strptime("re.match( r'([^\s]+)',str)", "%Y/%m/%d").strftime("%Y-%m-%d")

print(x)
print(new_x)

(pic) for code and error type

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    Have you considered `.replace('-', '/')` (or vice versa depending on which you are actually trying to do)? – khelwood Sep 26 '22 at 10:02

3 Answers3

1

Your current syntax is not valid, because you are passing the call to re.match as a literal string. Instead, try doing a replacement on the date portion only via a regex replacement with a callback function:

import re
import datetime

str = "2017/09/15 07:11:00"
output = re.sub(r'^(\S+)', lambda m: datetime.datetime.strptime(m.group(1), "%Y/%m/%d").strftime("%Y-%m-%d"), str)
print(output)  # 2017-09-15 07:11:00
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

I converted it using simple string slicing like this:

import datetime

string = "2017/09/15 07:11:00"
string = string[0:10]
new_x = datetime.datetime.strptime(string, "%Y/%m/%d").strftime("%Y-%m-%d")
print(new_x)
Mujtaba Mateen
  • 202
  • 2
  • 7
1

First of all you have to convert string to datetime object and than you can convert a datetime.

import datetime

str = "2017/09/15 07:11:00"

converted_time = datetime.datetime.strptime(str, "%Y/%m/%d %H:%M:%S")
print(converted_time.strftime("%Y-%m-%d %H:%M:%S"))

or if datetime object is not needed than you can just use a replace:

str = "2017/09/15 07:11:00"
str = str.replace("/", "-")
print(str)
SerSergious
  • 449
  • 2
  • 5
  • 21