Fetch hourly data - python

I am calculating the hour delta as below
ct = time.time() * 1000 // milliseconds
pt = ct - (1000*60*60*1) // 1 hour
The above code will give me the hour timestamp. How can I use the above code to get the past 20 days data hour by hour?

from datetime import datetime, timedelta
times = [datetime.now() - timedelta(hours=n) for n in range(24*20)] #±smh like this

Related

How to calculate time difference in python?

Example:
9:43 - 17:27 - how many hours and minutes elapsed between those times ?
Here is one approach to get the number of total minutes:
from datetime import datetime
s = '9:30 - 14:00 ; 14:30 - 16:30'
sum(((b-a).total_seconds()/60 for x in s.split(' ; ')
for a,b in [list(map(lambda t: datetime.strptime(t, '%H:%M'), x.split(' - ')))]))
Output: 390.0
If you know that the time periods will never span midnight, then you could simply split the time strings with time.split(":") and do the math yourself with the hours and minutes.
However, the correct solution would be to import the datetime module and calculate the timedelta.
This example could be condensed. I intentionally made it verbose without knowing exactly how you're getting your inputs:
from datetime import datetime
times = [
"9:30",
"14:00",
"14:30",
"16:30"
]
#Just using today's date to fill in the values with assumption all times are on the same day.
year = 2022
month = 6
day = 9
date_times = []
for time in times:
split_time = time.split(":")
hour = split_time[0]
minutes = split_time[1]
timestamp = datetime.datetime.today(year=year, month=month, day=day, hour=hour, min=minutes)
date_times.append(timestamp)
total_seconds = 0
for i in range(1, len(date_times), 2):
delta = date_times[i] - date_times[i-1] # The timedelta object returned will have days, seconds, milliseconds
total_seconds += delta.days * 86400 + delta.seconds
hours = total_seconds // 3600 # Integer division
minutes = round((total_seconds % 3600) / 60) # Change depending on if you want to round to nearest, or always up or down.

How to convert object datetime.time.now() to object datetime.timedelta()?

I'm using the datetime.time.now() for the current time, i.e. I want to perform an operation that counts in the totals of the hours (e.g. 1h:45min - 0h:50min). I cannot convert the current time to the datetime.timedelta object.
There is no datetime.time.now() — you must mean datetime.now() which returns a datetime instance which has a year, month, and day as well as the time of day. If you want a different time on the same day you can use its attributes to construct one.
If you subtract two datetimes the result is a timedelta.
You can also subtract an arbitrary timedelta from a datetime (resulting in another datetime).
Note that timedelta instances only have the attributes days, seconds, and microseconds, so if you want to know how long they are in hours and minutes, you have to manually calculate them.
Here's an example of doing all of these things.
from datetime import datetime, timedelta
now = datetime.now() # Current time.
# Construct a time on the same day.
sunrise = datetime(now.year, now.month, now.day, hour=6, minute=58)
if sunrise > now: # Future
delta = sunrise - now
when = 'will be in'
ago = ''
else: # Past
delta = now - sunrise
when = 'happened'
ago = 'ago'
days = delta.days
seconds = delta.seconds
hours = delta.seconds//3600
minutes = (delta.seconds//60) % 60
print(f'sunrise {when} {hours} hours {minutes} minutes {ago}')
print(f'30 minutes before sunrise today is {sunrise - timedelta(minutes=30)}')
I think I've found it; I wanted to compare the current time with the sunrise and sunset that Python itself retrieved.
I've done it this way now (so the next one can do it too)
import datetime as dt
DTN = dt.datetime.now()
H = int(DTN .strftime("%H"))
M = int(DTN .strftime("%M"))
S = int(DTN .strftime("%S"))
t1 = dt.timedelta(hours= H, minutes= M, seconds=S)
t2 = dt.timedelta(hours= 1, minutes= 0, seconds=0)
if t1 > t2:
timeCal = t1-t2 }
elif t1<t2:
timeCal = t2-t1
else:
timeCal = t1+t2
print(timeCal)
actual time = 20:00:00
result: 19:00:00

accelerometer is sampled at high frequency , how to convert UTC time to float time?

import pandas as pd
df = pd.DataFrame(['Time':['16:47:55.510','16:47:55.511','16:47:55.410']})
df
output:
Time
0 16:47:55.510
1 16:47:55.511
2 16:47:55.410
how to convert this time values to float value using python?
If the time is in h:m:s.ms format you can do something like this:
hours, minutes, seconds = df.Time[0].split(':')
total_seconds = int(hours) * 3600 + int(minutes) * 60 + float(seconds)

How to count future time delta when parameter is only hour and minute? Python

from datetime import datetime, timezone
time = input('Insert time: ')
f = '%H:%M'
now = datetime.now(timezone.utc).strftime(f)
diff = (datetime.strptime(time, f) - datetime.strptime(now, f)).total_seconds()
print(f'{diff} seconds')
print(f'{diff / 60 / 60} hours')
If the current time is 7:00 and I want a countdown for 2:00 the next day, it gives a negative time delta because it calculates it for the current day.
Expected output is: 18 hours
Reality: -6 hours
Any ideas on what's the best way to implement this? I don't want the user to input dates, just hour:minute.
Edit: Time format is 24 hours and only Hour:Minute (i.e 07:00, 18:30)
Objective is to avoid a negative time delta when the current time is 07:00 (7AM, today) and you enter 02:00 (2AM, the next day). The code is counting it 02:00 (2AM, the same day).
Something along these lines:
from datetime import datetime, date, time, timedelta
value = input('Insert time:')
t = time(*map(int, value.split(':')))
target = datetime.combine(date.today(), t)
now = datetime.now()
if target < now:
target += timedelta(days=1)
print(target - now)
Create a complete datetime timestamp by combining the input time with today's date. If that's before now, add a day to it.

scaling current time to a range in python

I want to scale the current time in a range. Like my start time is 08:00 hours and end time is 19:00 hours which is a 11 hr period. scaled value of my start time should be 0 and scaled value of my end time should be 11. Times like 10:00 and 10:30 should be scaled as 1 and 1.5 respectively.My code
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M")
start_time = '08:00'
end_time = '19:00'
The above code is reading the variable as strings and I'm not able to perform calculations on them. Can some one help me achieving the scaling.
Thanks
Change now.strftime("%H:%M") to now.strftime("%H%M")
This way you can convert it to an integer, so you have 1000 instead of 10:00 and you can use addition and subtraction
You can extract hours and minutes from your time using datetime.hour and datetime.minute.
To get the scaled value you want, for the range you specified (08:00 to 19:00), you can have :
from datetime import datetime
now = datetime.now()
if(8 <= now.hour <= 19):
scaled_time = now.hour - 8
scaled_time += now.minute / 60
Hope it's help.
Edit: you can change 8 and 19 to variables that contain your start and end time, so you can easily modify them
You can divide timedelta objects obtained from subtracting two datetime objects.
>>> from datetime import datetime
>>> start = datetime(2019, 12, day=19, hour=8, minute=0)
>>> end = datetime(2019, 12, day=19, hour=19, minute=0)
>>> now = datetime.now()
>>> print((now - start) / (end - start))
0.7824158481565656
8 to 19 is exactly 11 hours, so you don't need to scale it just use current time minus to 8 o'clock. so problem is down to change string to hours in decimal.
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M")
start_time = '08:00'
end_time = '19:00'
def conv(s):
l = s.split(':')
h = int(l[0])
m = int(l[1])
return h+m/60
st = conv(start_time)
# et = conv(end_time)
n = conv(current_time)
scaled = n-st
print(scaled)

Categories