1

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
David Buck
3,88640 gold badges54 silver badges74 bronze badges
asked Oct 30, 2019 at 22:51

2 Answers 2

2

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 Oct 30, 2019 at 23:03
Sign up to request clarification or add additional context in comments.

8 Comments

thanks!! for example i have this column of dates, but give me error: f'{df.at[idx,'fecha_vencimiento'].month}/{df.at[idx,'fecha_vencimiento'].day}/{df.at[idx,'fecha_vencimiento'].year}
Try using the dt accessor function, f'{df.at[idx,'fecha_vencimiento'].dt.month}/{df.at[idx,'fecha_vencimiento'].dt.day}/{df.at[idx,'fecha_vencimiento'].dt.year}'
give me SyntaxError: invalid syntax :(
df.at[idx,'fecha_vencimiento'] = f'{df.at[idx,'fecha_vencimiento'].dt.month}/{df.at[idx,'fecha_vencimiento'].dt.day}/{df.at[idx,'fecha_vencimiento'].dt.year}'
What is the output of type(df.at[idx,'fecha_vencimiento'])? That is, what do the date values currently look like? Strings, datetime values, timestamps, etc.
|
2

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 Nov 24, 2022 at 11:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.