Epoch Difference in Python
The difference between the given epochs can be determined by converting the struct_time
object to seconds using the mktime
method of the time
module.
Let's find the difference between the current time, specified in the epoch format, and the date '11/12/2023 19:25'
. First, we get epoch using the time
method:
now = time.time()
Then we transform the given date using the strptime
method. We write the date into its first parameter, and its format into the second parameter:
dt = time.strptime('11/12/2023 19:25', '%d/%m/%Y %H:%M')
print(dt)
As a result, we get the object struct_time
:
time.struct_time(tm_year=2023, tm_mon=12,
tm_mday=11, tm_hour=19, tm_min=25, tm_sec=0,
tm_wday=0, tm_yday=345, tm_isdst=-1)
Next, we convert struct_time
into seconds using the mktime
method and write the result to the dt_epoch
variable. Then we find the difference between the current epoch and dt_epoch
. The full code will look like this:
now = time.time()
dt = time.strptime('11/12/2023 19:25', '%d/%m/%Y %H:%M')
dt_epoch = time.mktime(dt)
res = now - dt_epoch
print(res) # 7937111.23894763
To get the number of minutes from this result, you need to divide it by 60
:
print(res / 60) # 132299.33016448814
Given date:
dt = '24/07/2015 16:1'
Find the number of seconds that have passed from the current time to this date.
Two dates are given:
dt1 = '12/02/23 10:12:54'
dt2 = '31/12/24 19:38:21'
Find the number of seconds that elapsed between the second and first dates.
Modify the solution to the previous problem to find the number of days that have elapsed between two dates.