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
2 Answers 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
Alexander
111k32 gold badges212 silver badges208 bronze badges
Sign up to request clarification or add additional context in comments.
8 Comments
salem1992
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}
Alexander
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}'salem1992
give me SyntaxError: invalid syntax :(
salem1992
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}'
Alexander
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. |
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.
Comments
lang-py