Debbie
Debbie

Reputation: 969

Python - Date conversion

I'm using Python and I want to convert a date from the following formats:

'30th Sep 2018' or 'Mon 30th Sep 2018'

to the format:

'2018-09-30 00:00:00'

I already tried to use the strptime() and strftime() functions but I can't make this works with them.

Anyone know how to accomplish this in Python?

Upvotes: 1

Views: 690

Answers (3)

Pedro Lobito
Pedro Lobito

Reputation: 98861

The simplest way to convert from 30th Sep 2018 or Mon 30th Sep 2018 to 2018-09-30 00:00:00 is using dateutil.parser, i.e.:

from dateutil.parser import parse
d = "30th Sep 2018"
dd = "Mon 30th Sep 2018"
print parse(d)
print parse(dd)
# 2018-09-30 00:00:00
# 2018-09-30 00:00:00

For the opposite conversion, there's datetime.strptime, but I'm afraid it doesn't output ordinals (1st, 2nd) as you want, still, you can achieve the desired result using a small function, i.e.:

def ord(n):
    return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
x = datetime.datetime.strptime("2018-09-30 00:00:00", '%Y-%m-%d %H:%M:%S')
print "{} {}".format(ord(int(x.strftime('%d'))), x.strftime('%b %Y'))
# 30th Sep 2018

Upvotes: 2

Kev
Kev

Reputation: 56

You can use datetime.strptime and datetime.strftime for that like so:

from datetime import datetime

def convert1(string):
    conversion = '%d' + string[2:4] + ' %b %Y'
    dt = datetime.strptime(string, conversion)
    return dt.strftime('%Y-%m-%d %H:%M:%S')

def convert2(string):
    conversion = '%a %d' + string[6:8] + ' %b %Y'
    dt = datetime.strptime(string, conversion)
    return dt.strftime('%Y-%m-%d %H:%M:%S')

print(convert1('30th Sep 2018'))
print(convert2('Mon 30th Sep 2018'))

print(convert1('01st Sep 2018'))
print(convert2('Sun 02nd Sep 2018'))

This is the output:

2018-09-30 00:00:00
2018-09-30 00:00:00
2018-09-01 00:00:00
2018-09-02 00:00:00

I used the patterns as described in the documentation for datetime. I used sclicing to extract the th part of the date-string. In doing so I ensure that the functions also work for nd and st.

Upvotes: 1

user8354377
user8354377

Reputation:

print(datetime.strftime('%Y %m %d %X)

You can use strftime for change the style of date and time

Goto to

http://strftime.org/

For more inforamtion

Upvotes: 0

Related Questions