Python Strftime - Date Without Leading 0

Datetime Object without leading zero

You are confusing the formats of parsing (a string into a dt) and formatting (a dt into a string):

This works on linux (or online via http://pyfiddle.io):

import datetime 

dt = datetime.datetime.now()

# format datetime as string
print(datetime.datetime.strftime(dt, '%Y-%-m-%-d')) # - acts to remove 0 AND as delimiter

# parse a string into a datetime object
dt2 = datetime.datetime.strptime("1022-4-09", '%Y-%m-%d')

print(dt2)

Output:

2018-4-5
1022-04-09 00:00:00

The - when formatting a string acts to remove the leading 0 AND as delimiter - for parsing it only needs to be placed as delimiter - parsing works on on either 02 or 2 for %m


This works on Windows (VS2017):

from datetime import datetime, timedelta

loop_date = "1950-1-1"
date_obj = datetime.strptime(loop_date, '%Y-%m-%d')
date_obj += timedelta(days=1)
print(date_obj) # output the datetime-object

print(datetime.strftime(date_obj,'%Y-%#m-%#d')) # output it formatted

Output:

1950-01-02 00:00:00
1950-1-2

python strftime without leading 0

Your problem is not related to leading 0 in the %d, but is due to the abbreviated month.

Use %b (for "Jun"), not %B (for "June").

Get rid of leading zeros for date strings in Python?

@OP, it doesn't take much to do a bit of string manipulation.

>>> t=time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
>>> '/'.join( map( str, map(int,t.split("/")) ) )
'12/1/2009'

Why does %-d , or %-e remove the leading space or zero?

Python datetime.strftime() delegates to C strftime() function that is platform-dependent:

The full set of format codes supported varies across platforms,
because Python calls the platform C library’s strftime() function, and
platform variations are common. To see the full set of format codes
supported on your platform, consult the strftime(3) documentation.

Glibc notes for strftime(3):

- (dash) Do not pad a numeric result string.

The result on my Ubuntu machine:

>>> from datetime import datetime
>>> datetime.now().strftime('%d')
'07'
>>> datetime.now().strftime('%-d')
'7'

Python datetime formatting without zero-padding

The formatting options available with datetime.strftime() will all zero-pad. You could of course roll you own formatting function, but the easiest solution in this case might be to post-process the result of datetime.strftime():

s = mydatetime.strftime('%m/%d/%Y %I:%M%p').lstrip("0").replace(" 0", " ")

Add leading zero to the hours in a date and time string

I enjoy using pandas pd.to_datetime() function to turn objects into proper datetime objects given it has the infer_datetime_format parameter which comes in handy and can also speed up the process too. Furthermore, with strftime you can then extract only the part you are interested in (or remove the seconds in this case):

time = '12/13/2020 7:59'
import pandas as pd
import datetime as datetime
pd.to_datetime(time,infer_datetime_format=True).strftime('%m/%d/%Y %H:%M')

Outputs:

13/12/2020 07:59

Remove leading 0's for str(date)

You could format it yourself instead of using strftime:

'{0}/{1}/{2}'.format(d.month, d.day, d.year) // Python 2.6+

'%d/%d/%d' % (d.month, d.day, d.year)

Python strftime days without ZERO

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 '')


Related Topics



Leave a reply



Submit