How to format dates in python?

Asked

Viewed 11,353 times

4

When I do so:

  data = input('data [d/m/Y]: ')    
  print(data)

  data2 = datetime.strptime(data, "%d/%m/%Y")

  print(data2)

returns to me like this:

data [d/m/Y]: 17/08/2018

17/08/2018

2018-08-17 00:00:00

how do I format the date being dd/mm/yyyy and not appear time together?

2 answers

9

The method datetime.strptime serves to make the Parsing (probably why the P) of a date in a given format. That is, it takes a string, does Parsing and returns an object datime.

To transform an object datetime in a string again you can use:

  • The method datetime.strftime to return a string in the desired format.

    minha_data.strftime("%d/%m/%Y")
    
  • Use the method datetime.__format__ (Protocol format):

    • with the function format().

      format(minha_data, "%d/%m/%Y")
      
    • with str.format:

      "{:%d/%m/%Y}".format(minha_data)
      
    • or with the f-strings introduced in python 3.6

      f"{minha_data:%d/%m/%Y}"
      

See the code running on Repl.it.

3

If you want to use print try so:

import datetime

_data="12/09/2018"
_data2=datetime.datetime.strptime(_data, "%d/%m/%Y")
print(_data2)

2018-09-12 00:00:00

print("{}/{}/{}".format(_data2.day,_data2.month,_data2.year))

12/9/2018
  • We appreciate the contribution - yes, this more "manual" way works - but the best is to use the date formatting features already made available by the datetime object - either with the .strftime or with the special syntax for .format of strings.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.