Convert a str to datetime in Python

Asked

Viewed 4,854 times

8

I am creating a task manager that should receive a task with a deadline. This manager will check how many days left to the deadline and let you know when to arrive. However, I am having a problem when converting the input date on str for datetime.

I’m using Python 3 in Pycharm.

from datetime import datetime

data_hoje = hoje.strftime('%d/%m/%y')  # Descobrindo a data atual para 
posteriormente comparar com a data limite

input_data_limite = input('DATA LIMITE: ') # Entrando com a data limite 

data_limite = datetime.strftime(input_data_limite, '%d/%m/%y') # deveria 
converter em datetime mas da erro

print(data_limite) 

1 answer

10


strftime converts a date (a datetime) to a string (which is the opposite of what you want to do).

In case, you have the return of input, which is a string (and not a date), and is passing it to strftime, so make a mistake.

If you want to convert a string to a date, use strptime (note the "p" instead of the "f"). Ex:

from datetime import date, datetime

hoje = date.today()
input_data_limite = input('DATA LIMITE: ')
data_limite = datetime.strptime(input_data_limite, '%d/%m/%y')

diferenca = data_limite.date() - hoje
print(diferenca.days) # diferença em dias

Notice I used date() to convert the datetime for date, because from what I understand, you just want to take into account the date (day, month and year), without considering the time.

Finally, I calculate the difference between the dates, and the result is a timedelta, from which it is possible to extract the corresponding number of days.


An important detail is that the format %y (with lowercase "y"), accept the year with 2 digits. If you want to accept the format "dd/mm/yyyy" (4 digit year), use %Y - with a capital "Y".

Another detail is that strptime spear one ValueError if the string is in a format that does not correspond to the informed one. In this case, you could make a loop for the user to enter the date again, until it is in valid format:

while True:
    try:
        input_data_limite = input('DATA LIMITE: ')
        data_limite = datetime.strptime(input_data_limite, '%d/%m/%y')
        break
    except ValueError:
        print('Data em formato inválido, tente novamente')

About dates and formats

Just to complement, as I said here, here and here, dates have no format.

A date is just a concept, an idea: it represents a specific point in the calendar.

The date of "January 2, 1970", for example, represents this: the specific point of the calendar that corresponds to the 2nd of January of 1970. To express this idea in text form, I can write it in different ways:

  • 02/01/1970 (a common format in many countries, including Brazil)
  • 1/2/1970 (American format, reversing day and month)
  • 1970-01-02 (the ISO 8601 format)
  • Two January 1970 (in good Portuguese)
  • January 2nd, 1970 (in English)
  • 1970 年 1 月 2 日 (in Japanese)
  • and many others...

Note that each of the above formats is different, but all represent the same date (the same numerical values of the day, month and year).

Therefore, a datetime represents a date (a point on the timeline), but it alone does not have a format. A string can contain a text that represents a date in a specific format.

When you want to turn a string (like "10/20/2019") into a date, you are making a Parsing (which is the "p" of the method strptime). When you want to represent a date in a specific format (i.e., turn it into a string), you are doing a formatting (the "f" of the method strftime). Your mistake was trying to make a format when you actually wanted to make one Parsing.

  • 1

    Thank you so much! You helped a lot in what I’m trying to do. Really, I’m just trying to compare the dates, not taking into account the schedule.

  • 2

    When you want to turn a string (such as "10/20/2019") into a date, you are making a Parsing (which is the "p" of the strptime method). When you want to represent a date in a specific format (i.e., turn it into a string), you are doing a formatting (the "f" of the strftime method). Your mistake was trying to do a formatting when you actually wanted to do a Parsing. This question was really good to better understand what to do. Thank you, again

  • It’s the first time I use stackoverflow. I’m still not very familiar with the mechanics. But I’ll learn kkk Thanks again!

  • 1

    @Juninhosouza No problem, I took a while to understand how the site works, but over time we get the hang of it :-)

Browser other questions tagged

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