I have the following time:
1 days 04:05:33.623000
Is it possible, to convert the time in milliseconds?
Like this:
101133623.0
It's certainly possible.
1 day + 4 hours + 5 minutes + 33 seconds + 623 milliseconds =
24 * 60 * 60 seconds + 4 * 60 * 60 seconds + 5 * 60 seconds + 33 seconds + 0.623 seconds =
86400 seconds + 14400 seconds + 300 seconds + 33 seconds + 0.623 seconds =
101133.623 seconds
Just use multiplication
Function Below:
def timestamp_to_milliseconds(timestamp):
day, hour, minute, second, millisecond = timestamp.split(":")
seconds = int(day) * 24 * 60 * 60 + int(hour) * 60 * 60 + int(minute) * 60 + int(second)
seconds += float(millisecond) / 1000
milliseconds = seconds * 1000
return milliseconds
I found a possibility to solve the problem
result = timestamp.total_seconds()*1000
print(result)
101133623.0
Related
I want to retrieve data in milliseconds from binance plateform, through get historical klines inspired from client.get_historical_klines, but he answer me by: binance.exceptions.BinanceAPIException: APIError (code=-1120)
I devloped this function
def interval_to_miliseconds(interval):
ms = None
seconds_per_unit = {
"S": 1,
"s": 1000,
"m": 60 * 1000,
"h": 60 * 60 * 1000,
"d": 24 * 60 * 60 * 1000,
"w": 7 * 24 * 60 * 60 * 1000,
"M": 4 * 7 * 24 * 60 * 60 * 1000
}
how can I collect TPS transaction per second from binance
raise BinanceAPIException(response, response.status_code, response.text)
binance.exceptions.BinanceAPIException: APIError (code=-1120)
I would like to calculate the average slope of multiple numbers. For example:
I've been given 5 numbers (eg. 1.1523, 1.4626, 1.5734, 1.8583, 1.6899). I get a new number every 15 minutes and delete the oldest and want to calculate again the average slope.
I've already seen formulas but I don't really get how to calculate it when like the imaginary x-axis is the time. Like I have:
X: 14:00, 14:15, 14:30, 14:45, 15:00
Y: 1.1523, 1.4626, 1.5734, 1.8583, 1.6899
Assuming all times are in HH:MM format and we don't need to worry about passing midnight, this should work:
X = ['14:00', '14:15', '14:30', '14:45', '15:00']
Y = [1.1523, 1.4626, 1.5734, 1.8583, 1.6899]
minutes = [int(s[:2]) * 60 + int(s[3:]) for s in X]
slope = (Y[-1] - Y[0]) / ((minutes[-1] - minutes[0]) / 60)
print(slope)
slopes = [(Y[i] - Y[i - 1]) / ((minutes[i] - minutes[i - 1]) / 60) for i in range(1, len(X))]
print(slopes)
averageSlope = sum(slopes) / (len(X) - 1)
print(averageSlope)
Results:
0.5375999999999999
[1.2411999999999992, 0.44320000000000004, 1.1396000000000006, -0.6736000000000004]
0.5375999999999999
I could be wrong, but isn't average slope determined the same way as average velocity - which is Delta d / Delta t? If that is the case, shouldn't it be Delta Y / Delta X?
from datetime import datetime
X = ['14:00', '14:15', '14:30', '14:45', '15:00']
Y = [1.1523, 1.4626, 1.5734, 1.8583, 1.6899]
today = datetime.now()
avg = []
for i in range(len(X) - 1):
e = X[i + 1].split(":")
e = datetime(today.year, today.month, today.day, int(e[0]), int(e[1]))
s = X[i].split(":")
s = datetime(today.year, today.month, today.day, int(s[0]), int(s[1]))
deltaX = e - s
deltaY = Y[i + 1] - Y[i]
ans = (deltaY / deltaX.seconds) / 60
avg.append(f'{ans:.9f}')
print(avg)
['0.000005746', '0.000002052', '0.000005276', '-0.000003119']
Consider this data:
1 minute(s) 1 meter(s)
2 minute(s) 2 meter(s)
3 minute(s) 3 meter(s)
You should have a slope of 1 meter/minute, no matter how you cut the cake.
Likewise for this:
1 minute(s) 2 meter(s)
2 minute(s) 3 meter(s)
3 minute(s) 5 meter(s)
From 2 to 1 minutes, the average is 1 meters/minute, from 3 to 2 minutes its 2 meters/minute, and from 3 to 1 minutes its 1.5 meters/minute.
I am currently building a vaccination appointment program for college and I am trying to write the code to randomly assign a date that ranges anywhere from 1/1/2022-31/12/2022, alongside a time slot ranging from 8am-5pm. Each hour will have 100 slots. Every time a user is assigned a slot, 1 from the assigned slot will be deducted. I tried doing this with a table i built using pandas, but I didn't get very far. Any help would be greatly appreciated, thank you.
Here's my code for the table using pandas (in case it will be helpful):
import pandas
start_date = '1/1/2022'
end_date = '31/12/2022'
list_of_date = pandas.date_range(start=start_date, end=end_date)
df = pandas.DataFrame(list_of_date)
df.columns = ['Date/Time']
df['8:00'] = 100
df['9:00'] = 100
df['10:00'] = 100
df['11:00'] = 100
df['12:00'] = 100
df['13:00'] = 100
df['14:00'] = 100
df['15:00'] = 100
df['16:00'] = 100
df['17:00'] = 100
print(df)
What I would do is start by including the leading zero at the beginning of the hour for each column name. It's easier to extract '08:00' from a pandas Timestamp than '8:00'.
df['08:00'] = 100
df['09:00'] = 100
Then you can set the index to your 'Date/Time' column and use .loc to locate an appointment slot by the date in the row and the hour (rounded down) in the columns, and subtract 1 from the number of appointments at that slot. For example:
df.set_index('Date/Time', inplace=True)
user1_datetime = pd.to_datetime("2022-01-02 08:30")
user1_day = user1_datetime.strftime('%Y-%m-%d')
user1_time = user1_datetime.floor("h").strftime('%H:%M')
df.loc[user1_day, user1_time] -= 1
Result:
>>> df
08:00 09:00 10:00 11:00 12:00 13:00 14:00 15:00 16:00 17:00
Date/Time
2022-01-01 100 100 100 100 100 100 100 100 100 100
2022-01-02 99 100 100 100 100 100 100 100 100 100
2022-01-03 100 100 100 100 100 100 100 100 100 100
2022-01-04 100 100 100 100 100 100 100 100 100 100
2022-01-05 100 100 100 100 100 100 100 100 100 100
... ... ... ... ... ... ... ... ... ... ...
2022-12-27 100 100 100 100 100 100 100 100 100 100
2022-12-28 100 100 100 100 100 100 100 100 100 100
2022-12-29 100 100 100 100 100 100 100 100 100 100
2022-12-30 100 100 100 100 100 100 100 100 100 100
2022-12-31 100 100 100 100 100 100 100 100 100 100
To scale up, you can easily wrap this in a function that takes a list of datetimes for multiple people, and checks that the person isn't making an appointment in an hour slot with 0 remaining appointments.
Thank you Derek, I finally managed to think of a way to do it, and I couldn't have done it without your help. Here's my code:
This builds the table and saves it into a CSV file:
import pandas
start_date = '1/1/2022'
end_date = '31/12/2022'
list_of_date = pandas.date_range(start=start_date, end=end_date)
df = pandas.DataFrame(list_of_date)
df.columns = ['Date/Time']
df['8:00'] = 100
df['9:00'] = 100
df['10:00'] = 100
df['11:00'] = 100
df['12:00'] = 100
df['13:00'] = 100
df['14:00'] = 100
df['15:00'] = 100
df['16:00'] = 100
df['17:00'] = 100
df.to_csv(r'C:\Users\Ric\PycharmProjects\pythonProject\new.csv')
And this code randomly pick a date and an hour from that date:
import pandas
import random
from random import randrange
#randrange randomly picks an index for date and time for the user
random_date = randrange(365)
random_hour = randrange(10)
list = ["8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00"]
hour = random.choice(list)
df = pandas.read_csv('new.csv')
date=df.iloc[random_date][0]
df.loc[random_date, hour] -= 1
df.to_csv(r'C:\Users\Rich\PycharmProjects\pythonProject\new.csv',index=False)
print(date)
print(hour)
I haven't found a way for the program to check whether the number of slots is > 0 before choosing one though.
I import data from CSV using Python. I want to calculate the mean for every row and column using time-variable only. But the problem is the value is not in seconds.
How can I declare the related variable into time which is second instead of numeric value?
this is my data
--------------------------
|Responses|Time 1 | Time 2 | Time 3|
| abc |20 | 30 | 40 |
| bce |23 | 25 | 30 |
| cde |34 | 40 | 20 |
So, I want to calculate the sum time for each response
df.sum(axis = 1)
abc 90
bce 78
cde 92
df.sum(axis = 0)
Time 1 76
Time 2 95
Time 3 90
But actually I want it in minutes second which is
df.sum(axis = 0)
Time 1 1:16
Time 2 1:35
Time 3 1:30
Or it can be 1 minute 16 seconds or something. Anyone know how to do it?
Your question is not really well defined. You should follow the instructions, as suggested in the comments by jezrael.
As you said "Or it can be 1 minute 16 seconds or something.", I assumed that the output can simply be a string.
If you want the result as:
1:16, use to_minutes_seconds(x)
1 minute 16 seconds, use to_minutes_seconds_text(x)
from datetime import timedelta
def to_minutes_seconds(x):
# x is the current value to process, for example 76
td = timedelta(seconds=x)
# split x into 3 variables: hours, minutes and seconds
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
# return the required format, minutes:seconds
return "{}:{}".format(minutes, seconds)
def to_minutes_seconds_text(x):
td = timedelta(seconds=x)
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
if minutes > 1:
m = 'minutes'
else:
m = 'minute'
if seconds > 1:
s = 'seconds'
else:
s = 'second'
return "{} {} {} {}".format(minutes, m, seconds, s)
# Create the input dictionary
df = pd.DataFrame.from_dict({'Responses': [76, 95, 90, 781]})
# Change the total seconds into the required format
df['Time'] = df['Responses'].apply(to_minutes_seconds)
df['Text'] = df['Responses'].apply(to_minutes_seconds_text)
print(df)
Output:
Responses Time Text
0 76 1:16 1 minute 16 seconds
1 95 1:35 1 minute 35 seconds
2 90 1:30 1 minute 30 seconds
3 781 13:1 13 minutes 1 second
I have a dataframe that contains the duration of a trip as text values as shown below in the column driving_duration_text.
print df
yelp_id driving_duration_text \
0 alexander-rubin-photography-napa 1 hour 43 mins
1 jumas-automotive-napa-2 1 hour 32 mins
2 larson-brothers-painting-napa 1 hour 30 mins
3 preferred-limousine-napa 1 hour 32 mins
4 cardon-y-el-tirano-miami 1 day 16 hours
5 sweet-dogs-miami 1 day 3 hours
As you can see some are written in hours and others in days. How could I convert this format to seconds?
UPDATE:
In [150]: df['seconds'] = (pd.to_timedelta(df['driving_duration_text']
.....: .str.replace(' ', '')
.....: .str.replace('mins', 'min'))
.....: .dt.total_seconds())
In [151]: df
Out[151]:
yelp_id driving_duration_text seconds
0 alexander-rubin-photography-napa 1 hour 43 mins 6180.0
1 jumas-automotive-napa-2 1 hour 32 mins 5520.0
2 larson-brothers-painting-napa 1 hour 30 mins 5400.0
3 preferred-limousine-napa 1 hour 32 mins 5520.0
4 cardon-y-el-tirano-miami 1 day 16 hours 144000.0
5 sweet-dogs-miami 1 day 3 hours 97200.0
OLD answer:
you can do it this way:
from collections import defaultdict
import re
def humantime2seconds(s):
d = {
'w': 7*24*60*60,
'week': 7*24*60*60,
'weeks': 7*24*60*60,
'd': 24*60*60,
'day': 24*60*60,
'days': 24*60*60,
'h': 60*60,
'hr': 60*60,
'hour': 60*60,
'hours': 60*60,
'm': 60,
'min': 60,
'mins': 60,
'minute': 60,
'minutes':60
}
mult_items = defaultdict(lambda: 1).copy()
mult_items.update(d)
parts = re.search(r'^(\d+)([^\d]*)', s.lower().replace(' ', ''))
if parts:
return int(parts.group(1)) * mult_items[parts.group(2)] + humantime2seconds(re.sub(r'^(\d+)([^\d]*)', '', s.lower()))
else:
return 0
df['seconds'] = df.driving_duration_text.map(humantime2seconds)
Output:
In [64]: df
Out[64]:
yelp_id driving_duration_text seconds
0 alexander-rubin-photography-napa 1 hour 43 mins 6180
1 jumas-automotive-napa-2 1 hour 32 mins 5520
2 larson-brothers-painting-napa 1 hour 30 mins 5400
3 preferred-limousine-napa 1 hour 32 mins 5520
4 cardon-y-el-tirano-miami 1 day 16 hours 144000
5 sweet-dogs-miami 1 day 3 hours 97200
Given that the text does seem to follow a standardized format, this is relatively straightforward. We need to break the string apart, compose it into relevant pieces, and then process them.
def parse_duration(duration):
items = duration.split()
words = items[1::2]
counts = items[::2]
seconds = 0
for i, each in enumerate(words):
seconds += get_seconds(each, counts[i])
return seconds
def get_seconds(word, count):
counts = {
'second': 1,
'minute': 60,
'hour': 3600,
'day': 86400
# and so on
}
# Bit complicated here to handle plurals
base = counts.get(word[:-1], counts.get(word, 0))
return base * count