In Python, we can convert a date to a string by:
>>> import datetime
>>> datetime.date(2002, 12,4).isoformat()
'2002-12-04'
How can we format the output to be '20021204', i.e. without dashes?
There are two functions, but I don't know how to specify the format:
date.strftime(format)
Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. For a complete list of formatting directives, see sectionstrftime()
andstrptime()
Behavior.
and
date.__format__(format)
Same asdate.strftime()
. This makes it possible to specify format string for a date object when usingstr.format()
. See sectionstrftime()
andstrptime()
Behavior.
1. Select the date cells you will remove the dashes, slashes, or hyphens from, right click, and select Format Cells from the context menu. 2. In the Format Cells dialog, under the Number tab, click to activate Custom in the Category list box, type the date code mmddyyyy into the Type box, and click the OK button.
The %f and %m can be used for one or two digit months. When a format specifier contains %f, single digit months are displayed as a single digit. When using %m, single digit months are displayed with a leading zero. For example, %f %e %Y will display the date 2 5 2018 with a single digit for the month.
If your dates are formatted with forward slashes (/), you are going to enter a forward slash into BOTH the Find what and Replace with fields. If your dates are formatted with dashes (-), then use dashes. Then click Replace All. (The keyboard shortcut for Replace All is Alt + A .)
You are using the wrong tool for your job, use strftime
>>> datetime.date(2002, 12,4).strftime("%Y%m%d")
'20021204'
For details on using strftime and strptime, refer strftime() and strptime() Behavior
For your particular case, I will quote the relevant excerpt
alternatively, you could have always removed or replaced the hyphen from the isoformat
>>> str(datetime.date(2002, 12,4)).translate(None,'-')
'20021204'
You can use '%m%d%Y
as your format :
>>> d=datetime.date(2002, 12,4)
>>> d.strftime('%m%d%Y')
'12042002'
Or in your first code, you can use str.replace
:
>>> datetime.date(2002, 12,4).isoformat().replace('-','')
'20021204'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With