Litwos
Litwos

Reputation: 1338

Convert full month and day name to short ones

I have a series of dates of this format: '2015 08 01' or '2015 12 11' and I want to convert them to this format: '2015 8 1' or '2015 12 11'. Basically, if the month and day sub-strings have a 0 at the start, that should be eliminated.

For example: The '2015 08 01' date string of the format ("%Y %m %d"), has the month number as 08 and day number as 01. I want the resulting date to be: '2015 8 1', where the month is converted from 08 to 8 and the day from 01 to 1.

I tried:

from datetime import datetime
str_date = '2015 08 01'
data_conv = datetime.strptime(str_date, "%Y%m%e")

but I get this error:

ValueError: 'e' is a bad directive in format '%Y%m%e'

Upvotes: 0

Views: 106

Answers (2)

S. de Melo
S. de Melo

Reputation: 856

Just remove the leading zeroes:

' '.join([x.lstrip('0') for x in str_date.split()])

Upvotes: 2

Hackaholic
Hackaholic

Reputation: 19733

it should be d:

>>> data_conv = datetime.strptime(str_date, "%Y %m %d")
>>> data_conv
datetime.datetime(2015, 8, 1, 0, 0)

Upvotes: 1

Related Questions