Compare dates in Python

Asked

Viewed 6,030 times

4

Good afternoon ! I need to solve the following scenario in python: I have one or more files . txt in a folder, but I want to return only the files that have the modification date according to the date I want (initial and final), but I’m not able to make this comparison as date with the user input:

import re
import os
from datetime import datetime as dt


#definindo datas
dtEntradaInicial = input('Data inicial: ')
dtEntradaFinal = input('Data final: ')

print(datetime.strptime(dtEntradaInicial, "%d/%m/%y").date())
print(datetime.strptime(dtEntradaFinal, "%d/%m/%y").date())

#testando retorno de data de modificação do arquivo
modificacao = datetime.fromtimestamp(os.path.getmtime('/c:/arquivoteste.txt'))
print('A data de modificação do arquivo é: ', modificacao)

if modificacao >= dtEntradaInicial and modificacao <= dtEntradaFinal:
   print('Consegui comparar datas com sucesso!')
  • 1

    dtEntradaInicial and dtEntradaFinal are strings. You’re converting strings to date, but you’re not saving anywhere.

2 answers

8


You are converting user input to date but it is not keeping the result.

You can save the converted input to a variable. Ex.:

from datetime import datetime

# Recebendo input do usuário (como string)
input_data_inicial = input('Data inicial:')
input_data_final = input('Data final:')

# Convertendo input para datetime.datetime
data_inicial = datetime.strptime(input_data_inicial, "%d/%m/%y")
data_final = datetime.strptime(input_data_final, "%d/%m/%y")

# apenas para demonstração atribui um valor 'hard-coded' para data_modificao
data_modificacao = datetime.now()

if data_inicial <= data_modificacao <= data_final:
    print('data_modificacao está entre o período selecionado')
else:
    print('data_modificacao está fora do período selecionado')

See code in action on Repl.it

  • 1

    It is not common in Python to prefix the type of a variable with a mnemonic of its type - "dt" in the case of variables such as "dtEntradaInicial". It is not forbidden, and there are times when it can help, it is true. Since by coincidence the AP uses these prefixes, and the problem in question has precisely to do with this, I thought it would be nice to reflect this in the answer. So I edited it to better reflect the types in each moment. (variable is input as strEntradaInicial, and then converted to another type).

  • @jsbueno I had only modified his code. But editing is very welcome. It makes sense and greatly improves the response. Thank you.

  • 1

    @fernandosavio Worth remembering also that you can do a < x < b in Python to check if x is among a and b.

  • Since the answer can improve, I will edit the question so that it not only reflects the example cited by the OP but becomes more useful. Thank you @Andersoncarloswoss

4

Taking advantage of the logic demonstrated in response of the fernandosavio and integrating with the my other answer on how to list recent files from a directory, you can do something like:

import time

from datetime import datetime
from pathlib import Path

def filtro_data_modificacao(inicial, final, *, formato='%d/%m/%y'):

    # Gera o timestamp a partir das datas de entrada:
    inicial = time.mktime(datetime.strptime(inicial, formato).timetuple())
    final = time.mktime(datetime.strptime(final, formato).timetuple())

    def filtro(arquivo):
        return inicial <= arquivo.stat().st_mtime <= final

    return filtro

diretorio = Path('/seu/diretorio')
arquivos = directory.glob('*.txt')
arquivos_modificados = filter(filtro_data_modificacao('01/09/18', '05/09/18'), arquivos)

for arquivo in arquivos_modificados:
    print(arquivo)

So in doing filtro_data_modificacao('01/09/18', '05/09/18') you generate a filter that will return true whether a particular file has been modified in this range. You can still, if necessary, define the format of the entry if, for example, you need to inform the year with four digits:

filter(filtro_data_modificacao('01/09/2018', '05/09/2018', formato='%d/%m/%Y'), arquivos)

Browser other questions tagged

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