Manas Chaturvedi
Manas Chaturvedi

Reputation: 5550

'e' is a bad directive in format '%e %B %Y'

I'm trying to convert a string given in the "DD MM YYYY" format into a datetime object. I expect the day integer in my output to consist of a single digit if the day in the date is in single digits. For example, the input '1 May 2014' should be converted to '1 May 2014' after converting into a datetime object instead of '01 May 2014'.

For this purpose, I have used the %e format for converting the day in my output date. Here's the code for the same:

import datetime
from datetime import timedelta

s = "1 July 2013"
d = datetime.datetime.strptime(s, "%e %B %Y")  

print d.strftime("%e %B %Y")

However, I'm getting the following error:

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

What's wrong with the formatting ? I'm using Python 2.7, if that helps.

Upvotes: 3

Views: 9017

Answers (3)

unutbu
unutbu

Reputation: 880587

%e is not a format code guaranteed to be processable by Python's datetime.strftime. Consult the table here for the list of format codes Python is guaranteed to support. However, since CPython's strftime calls the underlying C library's strftime, on some OS's, such as Linux, the %e format code exists.


The CPython source code says,

Other codes may be available on your platform. See documentation for\n\ the C library strftime function.\n"


There is no other format code (guaranteed to exist) which behaves like %e. So if your system does not have %e or you want your code to be cross-platform compatible, use string formatting, as shown by Zacrath or Jon Clements.

Upvotes: 7

Jon Clements
Jon Clements

Reputation: 142216

You can intermix string formatting and attribute access with the strftime style using str.format, eg:

from datetime import datetime

s = "1 July 2013"
d = datetime.strptime(s, "%d %B %Y")
 # 2013-07-01 00:00:00
out = '{0.day} {0:%B %Y}'.format(d)
# 1 July 2013

Upvotes: 5

Zacrath
Zacrath

Reputation: 556

There doesn't appear to be a directive for what you want. You can either make do with the zero padding or you can change the last line to print d.strftime("%d %B %Y").lstrip('0').

Upvotes: 2

Related Questions