2

Specifically I am having problems with using %-d and %-m on Windows.

The error I am getting is simple

output_dict.update({"DOB1": f"{dob.strftime('%-m/%-d/%Y') if not dob is None else 'UniqueID' + str(row)}"})
ValueError: Invalid format string

My format string looks like this:

dob.strftime('%-m/%-d/%Y')

I am fairly certain that this is because I am windows but I was wondering if there was a platform independent way of fixing this problem or if I am doing something else wrong which is causing this error.

I saw something about %e being used for the month in windows strftime but it replaces the 0 with a space instead but this is undesirable. I am trying to get these exact outputs (I use a similar format string later) 1/1/2000 and January 1 2000.

I would prefer not to use a solution like {dob.year} ect because I already have a format string that this is being placed in.

I would appreciate any ideas surrounding best practices and how I can implement a solution to this. Thank you.

Ryan Schaefer
  • 3,047
  • 1
  • 26
  • 46
  • can you show what is in your varialbe dob – ncica Jul 24 '19 at 15:31
  • 1
    Use a `#` instead of a `-` on Windows, as said there : https://stackoverflow.com/questions/28894172/why-does-d-or-e-remove-the-leading-space-or-zero#comment96325960_28916983 – Jona Jul 24 '19 at 15:35
  • @jona that solved the problem could you flesh it out into a full answer for future readers? – Ryan Schaefer Jul 24 '19 at 16:00

1 Answers1

10

A part of the answer is buried in this SA comment : Why does "%-d", or "%-e" remove the leading space or zero?

On Windows, you should use # to avoid the zero-padding (it replaces the - on Unix systems).

Here is a small example :

>>> from datetime import datetime
>>> datetime(2015, 3, 5).strftime('%d')
'05'
>>> datetime(2015, 3, 5).strftime('%-d')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid format string
>>> datetime(2015, 3, 5).strftime('%#d')
'5'

Unfortunately, I don't have a cross-platform solution.

Jona
  • 1,218
  • 1
  • 10
  • 20