Unix timestamp conversion to time with microsecond accuracy of seconds - python

I have 1000 of UYC timestamps in csv file, I want to convert it into date and time but I am only interested in second like
Timestamps= 1666181576.26295,
1666181609.54292
19/10/2022 15:45:25.34568
from that I only have interest in 25.34568 seconds, also the numbers after points. How can I get this type of conversion in python? Mostly the search on the internet is interested in conversation from UTC to time and date but I also want precision in seconds.

from datetime import datetime
from decimal import Decimal
ts = 1666181576.26295
timestamp = datetime.fromtimestamp(ts)
result = timestamp.second + Decimal(timestamp.microsecond)/1000000
print(result)
Will result in 56.26295

You can use datetime,
from datetime import datetime
ts = 1666181576.26295
mseconds = datetime.utcfromtimestamp(ts).microsecond

Simplest way I can see to do this is by splitting the timestamp to output everything from seconds onwards
timestamp = 1666181609.54292
temp = datetime.utcfromtimestamp(timestamp)
output = str(temp)
print(output[17:])

Related

Python Datetime strptime always to precision of millisecond

I am trying to convert strings e.g. "2010-01-01 10:09:01" into datetime to the precision of milliseconds. However even after adding 0 milliseconds at the back of the string e.g. "2010-01-01 10:09:01.000", the datetime always truncates the milliseconds part off. How do I make sure the datetime is always to the precision of millisecond even if there are 0 milliseconds in the timestamp? Thanks! :)
truncating the millisecond off
If I understood you correctly, you can use datetime.microseconds():
from datetime import datetime
a = datetime.strptime("2010-01-01 10:09:01.020", "%Y-%m-%d %H:%M:%S.%f")
print(a.microsecond) # >> 20000
print(a.microsecond//1000) # >> 20
And you can add if blocks or something that you need.
This is inside of value "a":

How to use milliseconds instead of microsenconds in datetime python

A client has specified that they use DateTime to store their dates using the format 2021-06-22T11:17:09.465Z, and so far I've been able only to obtain it in string dates, because If I want to maintain the milliseconds it saves them like 2021-06-22T11:17:09.465000.
Is there any possible way to force DateTime to use milliseconds instead of microseconds? I'm aware of the %f for microseconds in the format, but I've tried everything I can think of to reduce those 3 decimals while keeping it DateTime with no results however.
I suggest to use the timespec parameter, as described in python docs https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat:
>>> from datetime import datetime
>>> datetime.now().isoformat(timespec='minutes')
'2002-12-25T00:00'
>>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
>>> datetime.now().isoformat(timespec='milliseconds')
'2021-12-02T14:03:57.937'
Something like this works:
from datetime import datetime
dt = datetime.now()
print(f"{dt:%Y/%m/%dT%H:%M:%S}.{f'{dt:%f}'[:3]}")
Hope I help.
I assume you're looking for this? See also my general comment at question.
The variable 3 in [:3] can be adjusted to your liking for amount of zeros in ms to ns range. Use the type() to show you its a DateTime object.
import time
from datetime import datetime
tm = time.time()
print(tm)
dt = str(tm).split('.')
print(dt)
timestamp = float(dt[0] + '.' + dt[1][:3])
dt_object = datetime.fromtimestamp(timestamp)
print(dt_object)
This prints for example:
tm : 1638463260.919723
dt : ['1638463260', '919723']
and
dd_object : 2021-12-02 17:41:00.919000
You can divide nanoseconds by 1000000000 to get seconds and by 1000000 to get milliseconds.
Here is some code that will get nanoseconds:
tim = time.time_ns()
You can then combine the output of this with the rest of the format. Probably not the cleanest solution but it should work.

strptime() error - Time from sensor with more than 24 hours (e.g. 24:01:53)

I am using datetime.strptime() to convert a string containing time and date from a sensor into a datetime object.
The code sometimes fails. Minimal example:
datetime.strptime('1/9/2021 24:01:53', '%d/%m/%Y %H:%M:%S')
Output error:
ValueError: time data '1/9/2021 24:01:53' does not match format '%d/%m/%Y %H:%M:%S'
I am guessing this has to do with the fact that the time is more than 23:59:59 - which seems to me a non-realistic time (I would think that 1/9/2021 24:01:53 could potentially be 2/9/2021 00:01:53 - a time format which I have never seen).
Is this a non-standard way of representing time or possibly a hardware/software issue with the sensor acquisition system? If it is a different way of representing time, how can I convert it to a standard datetime object?
Kind regards,
D.F.
If the hour exceeds 23 in a variable representing time, a good option is to create a timedelta from it, which you can then add to a datetime object. For given example that might look like
from datetime import datetime, timedelta
def custom_todatetime(s):
"""
split date/time string formatted as 'DD/MM/YYYY hh:mm:ss' into date and time parts.
parse date part to datetime and add time part as timedelta.
"""
parts = s.split(' ')
seconds = sum(int(x) * 60 ** i for i, x in enumerate(reversed(parts[1].split(':'))))
return datetime.strptime(parts[0], "%d/%m/%Y") + timedelta(seconds=seconds)
s = '1/9/2021 24:01:53'
print(custom_todatetime(s))
# 2021-09-02 00:01:53
Note: conversion of hh:mm:ss to seconds taken from here - give a +1 there if helpful.

How to convert milliseconds to date and time format?

I have a value in milliseconds in a Python program. For example: 1557975599999
And I would like to convert it to a string with days and hours, minutes, seconds. How can I do this?
To convert unix timestamp to datetime, you can use datetime.fromtimestamp(). The only problem, that your timestamp is in miliseconds, but function expect timestamp in seconds. To cut miliseconds you can divide timestamp to 1000.
Code:
from datetime import datetime
a = 1557975599999
date = datetime.fromtimestamp(a // 1000)
print(date)
Output:
2019-05-16 05:59:59
Upd.
#Daniel in comments noticed that fromtimestamp() accept floats, so we can save miliseconds from original timestamp. All we need is just to remove one symbol :D
date = datetime.fromtimestamp(a / 1000)
With Pandas’ to_datetime()
import pandas as pd
pd.to_datetime(a, unit='ms')
# Or with a dataframe(column):
df['date'] = pd.to_datetime(df['Millisecond_time'], unit='ms')

How to add a certain time to a datetime?

I want to add hours to a datetime and use:
date = date_object + datetime.timedelta(hours=6)
Now I want to add a time:
time='-7:00' (string) plus 4 hours.
I tried hours=time+4 but this doesn't work. I think I have to int the string like int(time) but this doesn't work either.
Better you parse your time like below and access datetime attributes for getting time components from the parsed datetime object
input_time = datetime.strptime(yourtimestring,'yourtimeformat')
input_seconds = input_time.second # for seconds
input_minutes = input_time.minute # for minutes
input_hours = input_time.hour # for hours
# Usage: input_time = datetime.strptime("07:00","%M:%S")
Rest you have datetime.timedelta method to compose the duration.
new_time = initial_datetime + datetime.timedelta(hours=input_hours,minutes=input_minutes,seconds=input_seconds)
See docs strptime
and datetime format
You need to convert to a datetime object in order to add timedelta to your current time, then return it back to just the time portion.
Using date.today() just uses the arbitrary current date and sets the time to the time you supply. This allows you to add over days and reset the clock to 00:00.
dt.time() prints out the result you were looking for.
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(7, 00)) + timedelta(hours=4)
print dt.time()
Edit:
To get from a string time='7:00' to what you could split on the colon and then reference each.
this_time = this_time.split(':') # make it a list split at :
this_hour = this_time[0]
this_min = this_time[1]
Edit 2:
To put it all back together then:
from datetime import date, datetime, time, timedelta
this_time = '7:00'
this_time = this_time.split(':') # make it a list split at :
this_hour = int(this_time[0])
this_min = int(this_time[1])
dt = datetime.combine(date.today(), time(this_hour, this_min)) + timedelta(hours=4)
print dt.time()
If you already have a full date to use, as mentioned in the comments, you should convert it to a datetime using strptime. I think another answer walks through how to use it so I'm not going to put an example.

Categories