Home > Mobile >  (Python) changing date format from from yyyy-mm-dd to yyyy/mm/dd
(Python) changing date format from from yyyy-mm-dd to yyyy/mm/dd

Time:09-26

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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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)
  • Related