Comparing two times in Hours using python - python-3.x

I've two dates with time zone formatted as ('%Y-%m-%dT%H:%M:%SZ')
Given_Time = '2020-02-12T02:12:12Z'
current_time = '2020-02-11T06:22:42Z'
I wanted to compare these two times in Hrs. I mean given date is how many hours behind the current time

import datetime
def time_diff(x, y):
x = datetime.datetime.strptime(x,'%Y-%m-%dT%H:%M:%SZ')
y = datetime.datetime.strptime(y,'%Y-%m-%dT%H:%M:%SZ')
return (x-y).total_seconds()/3600
time_diff(Given_Time, current_time)
19.825
time_diff(current_time, Given_Time)
-19.825

Related

How to get 1st calendar day of the current and next month based on a current date variable

I have a date variable calls today_date as below. I need to get the 1st calendar day of the current and next month.
In my case, today_date is 4/17/2021, I need to create two more variables calls first_day_current which should be 4/1/2021, and first_day_next which should be 5/1/2021.
Any suggestions are greatly appreciated
import datetime as dt
today_date
'2021-04-17'
Getting just the first date of a month is quite simple - since it equals 1 all the time. You can even do this without needing the datetime module to simplify calculations for you, if today_date is always a string "Year-Month-Day" (or any consistent format - parse it accordingly)
today_date = '2021-04-17'
y, m, d = today_date.split('-')
first_day_current = f"{y}-{m}-01"
y, m = int(y), int(m)
first_day_next = f"{y+(m==12)}-{m%12+1}-01"
If you want to use datetime.date(), then you'll anyway have to convert the string to (year, month, date) ints to give as arguments (or do today_date = datetime.date.today().
Then .replace(day=1) to get first_day_current.
datetime.timedelta can't add months (only upto weeks), so you'll need to use other libraries for this. But it's more imports and calculations to do the same thing in effect.
I found out pd.offsets could accomplish this task as below -
import datetime as dt
import pandas as pd
today_date #'2021-04-17' this is a variable that is being created in the program
first_day_current = today_date.replace(day=1) # this will be 2021-04-01
next_month = first_day_current + pd.offsets.MonthBegin(n=1)
first_day_next = next_month.strftime('%Y-%m-%d') # this will be 2021-05-01

How to calculate average datetime timestamps in python3

I have a code which I have it's performance timestamped, and I want to measure the average of time it took to run it on multiple computers, but I just cant figure out how to use the datetime module in python.
Here is how my procedure looks:
1) I have the code which simply writes into a text file the log, where the timestamp looks like
t1=datetime.datetime.now()
...
t2=datetime.datetime.now()
stamp= t2-t1
And that stamp variable is just written in say log.txt so in the log file it looks like 0:07:23.160896 so it seems like it's %H:%M:%S.%f format.
2) Then I run a second python script which reads in the log.txt file and it reads the 0:07:23.160896 value as a string.
The problem is I don't know how to work with this value because if I import it as a datetime it will also append and imaginary year and month and day to it, which I don't want, I simply just want to work with hours and minutes and seconds and microseconds to add them up or do an average.
For example I can just open it in Libreoffice and add the 0:07:23.160896 to 0:00:48.065130 which will give 0:08:11.226026 and then just divide by 2 which will give 0:04:05.613013, and I just can't possibly do that in python or I dont know how to do it.
I have tried everything, but neither datetime.datetime, nor datetime.timedelta allows simply multiplication and division like that. If I just do a y=datetime.datetime.strptime('0:07:23.160896','%H:%M:%S.%f') it will just give out 1900-01-01 00:07:23.160896 and I can't just take a y*2 like that, it doesnt allow arithmetic operations, plus if if I convert it into a timedelta it will also multiply the year,which is ridiculous. I simply just want to add and subtract and multiply time.
Please help me find a way to do this, and not just for 2 variables but possibly even a way to calculate the average of an entire list of timestamps like average(['0:07:23.160896' , '0:00:48.065130', '0:00:14.517086',...]) way.
I simply just want a way to calculate the average of many timestamps and give out it's average in the same format, just as you can just select a column in Libreoffice and take the AVERAGE() function which will give out the average timestamp in that column.
As you have done, you first read the string into a datetime-object using strptime: t = datetime.datetime.strptime(single_time,'%H:%M:%S.%f')
After that, convert the time part of your datestring into a timedelta, so you can easily calculate with times: tdelta = datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second, microseconds=t.microsecond)
Now you can easily calculate with the timedelta object, and convert at the end of the calculations back into a string by str(tdsum)
import datetime
times = ['0:07:23.160896', '0:00:48.065130', '0:12:22.324251']
# convert times in iso-format into timedelta list
tsum = datetime.timedelta()
count = 0
for single_time in times:
t = datetime.datetime.strptime(single_time,'%H:%M:%S.%f')
tdelta = datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second, microseconds=t.microsecond)
tsum = tsum + tdelta
count = count + 1
taverage = tsum / count
average_time = str(taverage)
print(average_time)

Duration Calculator in Python

I have been studying Python by myself since a month ago.
I want to make a duration calculator that shows the total time of each different duration.
For instance, there are two different flights I have to take, and I want to get the total time I would be in the airplanes. It goes like this.
a = input('Enter the duration: ') #11h40m
b = input('Enter the duration: ') #13h54m
#it may show the total duration
01d01h34m
Try this :
Edit : I tried to use strftime to format the 'duration' but had some issues with day.
So I did it manually (you can format it the way you wish)
import datetime
import time
# Convert str to strptime
a_time = datetime.datetime.strptime("11h40m", "%Hh%Mm")
b_time = datetime.datetime.strptime("13h54m", "%Hh%Mm")
# Convert to timedelta
a_delta = datetime.timedelta(hours = a_time.hour,minutes=a_time.minute)
b_delta = datetime.timedelta(hours = b_time.hour,minutes=b_time.minute)
duration = (a_delta + b_delta)
print(str(duration.days) + time.strftime('d%Hh%Mm', time.gmtime(duration.seconds)))
'1d01h34m'

Rounding datetime to the nearest hour

I have a question very similar to this one and this one but I'm stuck on some rounding issue.
I have a time series from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00'. Eventually I want output in the format .strftime('%Y%m%d.%H%M'). So for example I read my netCDF file as follows
import netCDF4
nc = netCDF4.Dataset(file_name)
time = np.array(nc['time'][:])
I then have
In [180]: time[0]
Out[180]: 365
In [181]: time[1]
Out[181]: 365.04166666651145
I then did
In [182]: start = datetime.datetime(1990,1,1)
In [183]: delta = datetime.timedelta(time[1])
In [184]: new_time = start + delta
In [185]: print(new_time.strftime('%Y%m%d.%H%M'))
19910101.0059
Is there a a way to "round" to the nearest hour so I get 19910101.0100?
You can round down with datetime.replace(), and round up by adding an hour to the rounded down value using datetime.timedelta(hours=1).
import datetime
def round_to_hour(dt):
dt_start_of_hour = dt.replace(minute=0, second=0, microsecond=0)
dt_half_hour = dt.replace(minute=30, second=0, microsecond=0)
if dt >= dt_half_hour:
# round up
dt = dt_start_of_hour + datetime.timedelta(hours=1)
else:
# round down
dt = dt_start_of_hour
return dt
Note that since we're using replace the values we're not replacing (like the timezone - tzinfo) will be preserved.
I don't think datetime provides a way to round times, you'll have to provide the code to do that yourself. Something like this should work:
def round_to_hour(dt):
round_delta = 60 * 30
round_timestamp = datetime.datetime.fromtimestamp(dt.timestamp() + round_delta)
round_dt = datetime.datetime.fromtimestamp(round_timestamp)
return round_dt.replace(microsecond=0, second=0, minute=0)

Count down to a week later from current date and time in Python?

I want to make an app that when run, it will get the current date and time from the user's computer, and then count down to a week later at the time of running.
So for example:
The user runs the app on 06-06-2017 11:00:00, it must do a count down to a deadline a week later and display the deadline date and time, and show a count down of how many days, hours, minutes and seconds are left.
EDIT:
So far I have only been able to get the date and time and the time increments normally per second. I am having difficulty decrementing it. Without the last line of the code the time decrements but does not update automatically. I have yet to find a way to perform a count down from a week in advance.
def updateTime():
X = 1
t = datetime.datetime.now()
s = t.replace(microsecond=0)
result = s - datetime.timedelta(seconds=X)
future = s + datetime.timedelta(days=7, hours=0, minutes=0, seconds=0)
lblTime.configure(text=result, font=("", 14))
lblTime.after(100, updateTime)
You definitely want to calculate the target time only once instead of getting it every time the updateTime handler runs. Furthermore, you can simply do arithmetic on datetime objects to get a timedelta object back which you can then display in your GUI.
Here is an example that is printing the output to the console. You can probably adjust this as needed to make it display in your GUI.
import datetime
target_time = datetime.datetime.now() + datetime.timedelta(days=7)
target_time = target_time.replace(microsecond=0)
def get_remaining_time():
delta = target_time - datetime.datetime.now()
hours = delta.seconds // 3600
minutes = (delta.seconds % 3600) // 60
seconds = delta.seconds % 60
print('{} days, {} hours, {} minutes, {} seconds'.format(delta.days, hours, minutes, seconds))
while True:
get_remaining_time()

Resources