How to convert timestamp into milliseconds in python - python-3.x

I am trying to write a basic script that can read in a timestamp as a string and convert it into milliseconds. The timestamps I am working with are in minute:second.millisecond format.
from datetime import datetime
timestamp_start = '54:12.123'
MSM = '%M:%S.%f'
zero = '00:00.000'
start_sec = (datetime.strptime(timestamp_start, MSM) - datetime.strptime(zero, MSM)).total_seconds()
start_ms = start_sec * 1000
print(start_ms)
This may be a round about approach, but I am first using datetime.strptime to get a datetime object, then subtracting by 0 in order to get a timedelta object, getting the total seconds of the timedelta object, and finally multiplying by 1000 to convert to milliseconds.
The above code works fine, except for any timestamps over an hour.
The issue that I am running into- the timestamps do not have an hour counter. For example: 1 hour, 5 minutes, and 30 seconds comes in as 65:30.000. datetime.strptime cannot recognize this format, as it only allows the minutes to be between 0 and 59.
How can I convert these timestamps into a format recognizable by datetime? Should I first get the timestamp into hour:minute:second:millisecond format? Keep in mind the end goal is to convert these timestamps into milliseconds. If there is a better approach any suggestions are more than welcomed!

'54:12.123' isn't really a timestamp, but elapsed time, and there's no built-in method in Python that can deal with elapsed time with a format string like a timestamp format.
Since the format string in question is simply minutes and seconds separated by a colon, and seconds and milliseconds separated by a period, you can easily parse it with the str.split method:
def convert(msf):
minutes, seconds = msf.split(':')
seconds, milliseconds = seconds.split('.')
minutes, seconds, milliseconds = map(int, (minutes, seconds, milliseconds))
return (minutes * 60 + seconds) * 1000 + milliseconds
so that convert('54:12.123') returns:
3252123

Related

Non-standard Julian day time stamp

I have a timestamp in a non-standard format, its a concatenation of a number of elements. I'd like to convert at least the last part of the string into hours/minutes/seconds/decimal seconds so I can calculate the time gap between them (typically of the order of 2-5 seconds).
I have looked at this link but it assumes a 'proper' Julian time. How to convert Julian date to standard date?
My time stamp looks like this
1380643373
It is set up as ddd hh mm ss.s
This timestamp represent 138th day, 06:43:37.3
Is there a datetime method of working with this or do I need to strip out the various parts (hh,mm,ss.s) and concatenate them in some way? As I am only interested in the seconds, if I can just extract them I could deal with that by adding 60 if the second timestamp is smaller than the first - i.e event passes over the minute change boundary.
If you're only interested in seconds, you can do:
timestamp = 1380643373
seconds = (timestamp % 1000) / 10 # Gives 37.3
timestamp % 1000 gives you the last three digits of timestamp. Then you divide that by 10 to get seconds.
If it's a string, you can take the last three characters by slicing it.
timestamp = "1380643373"
seconds = int(timestamp[-3:]) / 10 # Gives 37.3
It's pretty easy to convert the timestamp to a datetime using the divmod() function repeatedly:
import datetime
base_date = datetime.datetime(2000, 1, 1, 0, 0, 0) # Midnight on Jan 1 2000
timestamp = 1380643373
timestamp, seconds = divmod(timestamp, 1000) # Gives 1380643, 373
seconds = seconds / 10 # Gives 37.3
timestamp, minutes = divmod(timestamp, 100) # Gives 13806, 43
days, hours = divmod(timestamp, 100) # Gives 138, 6
tdelta = datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds) # Gives datetime.timedelta(days=138, seconds=24217, microseconds=300000)
new_date = base_date + tdelta

convert the h:m:s in minutes format

I have the following data. The idea is to multiply all the data.
however the minute column is in h:m:s format. So whenever i try to multiply i get an error.
and morever i need to convert the h:m:s in minutes format before i actually want to multiply.
tried with the following to convert this to minute
time1 = df['time']
time2 = time1.hour * 60 + time1.minute + time1.second
Create timedeltas by to_timedelta, convert to seconds by Series.dt.total_seconds and divide by 60:
df['Minutes'] = pd.to_timedelta(df['(MIN)']).dt.total_seconds().div(60)
If input valeus are python times also convert to strings:
df['Minutes'] = pd.to_timedelta(df['(MIN)'].astype(str)).dt.total_seconds().div(60)

Summing time fields over 24 hours in Power Query

I have a Power Query in excel linked to another file. This file has a time column. I understand that M language will not sum above 24 hours automatically without some work as it uses a datetime reference hence if I import a time of 25 hours it reverts back 2 hours to 1 hour...
In the 3rd column along in my image below using the second row as a reference, this is actually supposed to read 47:47:38. How can I get the instances where the value is above 24 hours to show the true hours?
I have tried using duration.hours(#hours()) this also does not work for some reason.
The same data from the source excel file is below also
Power Query doesn't have custom formats for how it displays data. If you have it read your data as a Duration instead of a DateTime it will display as [d].hh.mm.ss format, but still not with the total hours. Ultimately though this doesn't really matter because even when your data is formatted to display total hours in Excel, it's really being stored internally as days+hours+minutes+seconds. So how it displays in Power Query doesn't matter, as you can just use the hour formatting wherever you output the data to.
Now if you need to use the hours for a calculation between something that isn't another Duration, you can extract the hours by doing
Duration.Days([Your Hours]) * 24 + Duration.Hours([Your Hours])
Or now that I look at it, there is also a TotalHours function that gives you the hours plus mm:ss as a fractional amount of that
Duration.TotalHours([Your Hours])
Power BI doesn't handle this case very gracefully. A solution could be to convert the duration to a number to make it additive (so you can perform calculations and aggregations) and when you need to visualize it, to convert it to the desired format (HH:MM:SS).
Duration and Time are often confused. When such Excel files are read, the type of the column usually is DateTime, and date 1899-12-31 is added to the "time" part. You can change the data type of the column to be Decimal Number, but the "zero point" in Excel unfortunately is one day off (1899-12-30), so you need to subtract 1 from the result to get the actual "number of days" of the duration (i.e. 0.25 means 06:00:00).
So you must perform some conversion of the data. I would make a new column in the model to get the duration in the lowest granularity that I need (seconds in your example). In Power Query Editor add a custom column to calculate the duration in seconds (where Column1 is the name of the original duration column):
Duration in seconds = Duration.TotalSeconds([Column1] - #datetime(1899, 12, 31, 0, 0, 0))
Make sure the data type of this column is Whole Number (change it if necessary). Here 9144 seconds are calculated as 2 * 3600 + 32 * 60 + 24, or 02:32:24. Now you can calculate a sum on this column to get total duration in seconds for example. But when you visualize this column, don't do it directly, but make a measure to convert the data to the desired format. It could me made like this:
Measure Duration =
VAR duration_in_seconds = SUM(Sheet1[Duration in seconds])
VAR hours = ROUNDDOWN ( duration_in_seconds / 3600; 0 )
VAR minutes = ROUNDDOWN ( MOD ( duration_in_seconds; 3600 ) / 60; 0 )
VAR seconds = INT ( MOD ( duration_in_seconds; 60 ) )
RETURN hours & ":" & FORMAT(minutes; "00") & ":" & FORMAT(seconds; "00")
duration_in_seconds variable hold the total duration in seconds of the data in the context. From it we are calculating hours, minutes and seconds and constructing a string to represent the duration in the desired format. FORMAT is used to make sure there is a leading zero in case minutes or seconds are less than 10.
Here is how all three columns looks like when visualized:
Hope this helps!

Dynamodb TTL 24hours

Hi I am wonder about how to set the time to live in dynamo db.
I understand that I have to create a field, could be called ttl and set the value to be deleted, but in which format innodejs do I have to save to use for the ttl field for 20 or 24 hours?
Thanks for help.
From the official DynamoDB documentation:
TTL compares the current time in epoch time format to the time stored
in the Time To Live attribute of an item. [...]
Note
The epoch time
format is the number of seconds elapsed since 12:00:00 AM January 1st,
1970 UTC.
In Javascript, you can get the number of milliseconds since the epoch by doing Date.now(). Once you have that, you can divide everything by 1000 to get the seconds (also rounding to the nearest integer value) and finally add the number of seconds in the TTL that you want.
This means that if you want to set the expiration time 24 from now, you can easily set the TTL field with the value expirationTime calculated this way:
const SECONDS_IN_AN_HOUR = 60 * 60;
const secondsSinceEpoch = Math.round(Date.now() / 1000);
const expirationTime = secondsSinceEpoch + 24 * SECONDS_IN_AN_HOUR;

Total minutes from datetime value

How to get total time in minutes from datetime?
18/11/2013 07:31:04
The result should be: 451 min (it's 07*60 + 31).
Extract the hour and minute components of your date time with HOUR() and MINUTE() functions and combine them with this formula
=HOUR(A1)*60+MINUTE(A1)

Resources