Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python date string formatting

I want to remove the padded zeroes from a string-formatted python date:

formatted_date = my_date.strftime("%m/%d/%Y") # outputs something like: 01/01/2013
date_out = formatted_date.replace(r'/0', r'/').replace(r'^0', r'') 

The second replace doesnt work-- I get 01/1/2013. How do I match the zero only if it's next to the beginning of the string?

like image 275
kelorek Avatar asked Sep 10 '13 16:09

kelorek


People also ask

How do I format a date string in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

Is there a date format in Python?

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.


1 Answers

.replace() does not take regular expressions. You are trying to replace the literal text ^0.

Use str.format() to create a date format without zero-padding instead:

'{0.month}/{0.day}/{0.year}'.format(my_date)

and avoid having to replace the zeros.

Demo:

>>> import datetime
>>> today = datetime.date.today()
>>> '{0.month}/{0.day}/{0.year}'.format(today)
'9/10/2013'

If Python was compiled with the glibc library, then you could also use dashes in the format to suppress the padding:

my_date.strftime('%-m/%-d/%y')

but that is not nearly as portable.

like image 89
Martijn Pieters Avatar answered Sep 30 '22 20:09

Martijn Pieters