Calculating date with Python

0

I have a script that needs to make a difference between 2 dates collection of some files

In case the script collects the date of a .txt file (dt_log) and the current date of the system (dt_sys) and my difficulty is to find the difference between these 2 dates

Example

The file was created on 07/20/2018 10:05:55 AM The system date is 7/25/2018 11:10:02 AM

The return I would need to print is 120 hours (5 days = 120 hours)

Is it possible to do this?

Here's some code snippet:

# LOG DATE AND SYSTEM DATE
## LOG dt_log = os.stat(log[0]) dt_log = time.ctime(dt_log.st_ctime) dt_log = dt_log.split(' ') print("Hora da Log: ", dt_log[3])

## SYSTEM dt_sys = time.time() dt_sys = time.ctime(dt_sys) dt_sys = dt_sys.split(' ') print("Hora do Sys: ", dt_sys[3])

# CALCULATE DIFFERENCE BETWEEN DATES calc = int(dt_log[3] - dt_sys[3])

Code that takes the date of the file and the system:

    # LOG DATE AND SYSTEM DATE
## LOG
dt_log = os.stat(log[0])
dt_log = time.ctime(dt_log.st_ctime)
#dt_log = dt_log.split(' ')
print("Hora da Log: ", dt_log)

## SYSTEM
dt_sys = time.time()
dt_sys = time.ctime(dt_sys)
#dt_sys = dt_sys.split(' ')
print("Hora do Sys: ",dt_sys)
    
asked by anonymous 25.07.2018 / 20:12

1 answer

2

Yes, it is possible to do this with the datetime library and the strptime function, which transforms a string into a date according to a format.

from datetime import datetime

def diferenca_dias(d1, d2):
    d1 = datetime.strptime(d1, "%d/%m/%Y %H:%M:%S")
    d2 = datetime.strptime(d2, "%d/%m/%Y %H:%M:%S")
    return abs((d2 - d1).days * 24)

Example usage:

>>> d1 = '20/07/2018 10:05:55'
>>> d2 = '25/07/2018 11:10:02'
>>> print(diferenca_dias(d1, d2))
120

Sources:

link link

Edit: These "% d /% m /% Y% H:% M:% S" can be seen here: link

The difference_days function returns a timed record. To compare if the return is greater or less than a number of days, we can compare: if return_of_funcao > timedelta (days, seconds). To use timedelta () we should import it (from datetime import timedelta).

    
25.07.2018 / 21:03