Python strftime days without ZERO


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

‘4/5/1992’ YES

’04/05/1992′ NO

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

ValueError: Invalid format string
Asked By: salem1992



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 = - timedelta(21)
yest = f'{yest.month}/{}/{yest.year}'
>>> yest

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.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.