Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date without dash?

Tags:

python

date

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 section strftime() and strptime() Behavior.

and

date.__format__(format)
Same as date.strftime(). This makes it possible to specify format string for a date object when using str.format(). See section strftime() and strptime() Behavior.

like image 716
Tim Avatar asked Mar 27 '15 07:03

Tim


People also ask

How do you remove the date separator in Excel?

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.

What is %f in date format?

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.

What function could you use to replace lashes for dashes in a list of dates?

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


2 Answers

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

  • %Y Year with century as a decimal number. 1970, 1988, 2001, 2013
  • %m Month as a zero-padded decimal number. 01, 02, ..., 12
  • %d Day of the month as a zero-padded decimal number. 01, 02, ..., 31

alternatively, you could have always removed or replaced the hyphen from the isoformat

>>> str(datetime.date(2002, 12,4)).translate(None,'-')
'20021204'
like image 110
Abhijit Avatar answered Sep 27 '22 20:09

Abhijit


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'
like image 39
Mazdak Avatar answered Sep 27 '22 21:09

Mazdak