Python strftime days without ZERO

Question:

Why doesn’t the codes from this page work?: http://strftime.org/.
I want to output date and months without leading zeroes, like ‘m/d/yyyy’

e.g.:
‘4/5/1992’ YES

’04/05/1992′ NO

from datetime import datetime, timedelta, date
yest = datetime.strftime(datetime.now() - timedelta(21), '%-m-%-d-%Y')
print(yest)
ValueError                                Traceback (most recent call last)
<ipython-input-35-7c70a0a7eee5> in <module>
      1 from datetime import datetime, timedelta, date
----> 2 yest = datetime.strftime(datetime.now() - timedelta(21), '%-m-%-d-%Y')
      3 print(yest)

ValueError: Invalid format string
Asked By: salem1992

||

Answers:

That %-m option does state that the format is platform specific, so mileage may vary.

You can simply use f-strings in Python 3.

yest = datetime.now() - timedelta(21)
yest = f'{yest.month}/{yest.day}/{yest.year}'
>>> yest
'10/9/2019'

In the case of your dataframe explained in the comments:

df = pd.DataFrame({
    'fecha_vencimiento': [
        '12/25/2009', '01/05/2010', '04/13/2011', '']})

df['fecha_vencimiento'] = pd.to_datetime(
    df['fecha_vencimiento'], format='%m/%d/%Y', errors='coerce').apply(
        lambda x: f'{x.month}/{x.day}/{x.year}' 
        if pd.notnull(x) else '')
Answered By: Alexander

The %-d would give you the day without the leading 0 and %-m the month, but this format only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %#d, %#m.

Answered By: Juliana Schmidt
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.