Format date without dash?

In Python, we can convert the date to a string:

>>> import datetime >>> datetime.date(2002, 12,4).isoformat() '2002-12-04' 

How can we format the output as "20021204", i.e. without a dash?

There are two functions, but I do not know how to specify the format:

date.strftime(format)
Return a string representing a date driven by an explicit format string. Format codes related to hours, minutes or seconds will display 0 values. For a complete list of formatting directives, see strftime() and strptime() Behavior.

and

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

+5
source share
2 answers

You are using the wrong tool for your work, use strftime

 >>> datetime.date(2002, 12,4).strftime("%Y%m%d") '20021204' 

For more information on using strftime and strptime , consult strftime () and strptime () Behavior

In your particular case, I will give an appropriate passage

  • % Y A year with a century as a decimal number. 1970, 1988, 2001, 2013.
  • % m The month as a decimal number with zero margin. 01, 02, ..., 12
  • % d Day of the month as a decimal with zero margin. 01, 02, ..., 31

you could always remove or replace the hyphen from isoformat

 >>> str(datetime.date(2002, 12,4)).translate(None,'-') '20021204' 
+10
source

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' 
+4
source

Source: https://habr.com/ru/post/1216255/


All Articles