0

I want to change the string 'datetime.datetime(2018, 4, 15, 12, 59)' into the format '2018-04-15T12:59'.

I created a function that looks like:

def changeDateFormat(date):
    newDate = []
    for i in date.split('datetime')[2].split(','):
        newDate.append(re.sub('[() ]', '', i))
    newStr = newDate[0] + '-0' + newDate[1] + '-' + newDate[2] + 'T' + newDate[3] + ':' + newDate[4]
    return newStr

And it works.

However, I also want it to handle the case where if each unit is less than 10, I want to add a '0'. Right now it just adds a '0' regardless.

I can do it in a very inefficient way, but I wonder how I can do it in a smart way.

2
  • 3
    The nicer solution is avoiding ending up with the repr of a datetime object in the first place. Commented Apr 16, 2018 at 2:09
  • I'm really with @miradulo on this. Must you work with a repr-string? Why can't you have accesses to the actually datetime object? Commented Apr 16, 2018 at 2:11

3 Answers 3

1

I don't understand why you use the string representation of a datetime object but eval is your friend:

>>> import datetime
>>> eval('datetime.datetime(2018, 4, 15, 12, 59)').isoformat()
'2018-04-15T12:59:00'

eval documentation: https://docs.python.org/3/library/functions.html#eval

Sign up to request clarification or add additional context in comments.

1 Comment

"but eval is your friend" - Eh, I'd really advise not to use eval here - or anywhere. There's almost always a better way then using eval. It may be tempting to use eval, but I'd find something different instead. Please see _Why is using 'eval' a bad practice? _
1

I assume that you're trying to avoid using the datetime object, because it seems obviously confusing otherwise.

I can do it in a very inefficient way

You are actually not very far away, just one line.

def changeDateFormat(date):
    newDate = []
    for i in date.split('datetime')[2].split(','):
        newDate.append(re.sub('[() ]', '', i))

    pad = '-0' if newDate[1] < 10 else '-'
    newStr = newDate[0] + pad + newDate[1] + '-' + newDate[2] + 'T' + newDate[3] + ':' + newDate[4]
    return newStr

I'm afraid there isn't any smarter way if you're not using the datetime object.

1 Comment

Not that I really think the OP should be doing it this way (he really should try to get the actually datetime object and not the repr), but you could use re.findall to grab the digits and avoid all that substitution stuff with re.sub.
1

datetime.strftime and eval would be perfect here.

import datetime
# use eval to execute the string like a a command
dt = eval('datetime.datetime(2018, 4, 15, 12, 59)')

formatted_date = dt.strftime('%Y-%m-%dT%H:%M')

output: '2018-04-15T12:59'

Reference: strftime() and strptime() Behavior

2 Comments

I know it's tempting, but it really is best to avoid using eval. Please see Why is using 'eval' a bad practice?.
Well of course it would be a case by case scenario on whether eval is bad or not. In OP's case I don't see how using eval is bad. However, I understand the debate and why it should generally be avoided.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.