convert unix time to mysql datetime and include milliseconds - python

timestamp = 1539965545566873
timestamp = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S.{:03d}')
ValueError: year is out of range
I this include microseconds and milliseconds. So I can divide it by /1000 to lose the accuracy of microseconds, but I want to store milliseconds too.
Any idea how? Also, I'm using Django, if that matters.

A quick workaround:
timestamp = 1539965545566873
time, micro = divmod(timestamp, 1000000)
timestamp = datetime.utcfromtimestamp(time).strftime('%Y-%m-%d %H:%M:%S.')
timestamp += str(micro)
timestamp
>>>'2018-10-19 16:12:25.566873'
AFAIK utcfromtimestamp does not have a parameter that allows you to pass in microseconds.

Related

Unix timestamp conversion to time with microsecond accuracy of seconds

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:])

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 define a difference in time in seconds between a timestamp saved as a string and a current UTC timestamp

I am testing the difference between an actual UTC time and timestamp when my object was saved in a table (UTC). It must be not more than 60 seconds.
Example of timestamp_from_table (string from my site): 2021-02-05 13:51:52
After researching for options to make this, I came to this approach:
timestamp_from_table = driver.find_element_by_css_selector("my_locator").text
current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()) # current time converted to string
current_time_truncated = datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S") # cutting milliseconds
date_time_obj = datetime.strptime(timestamp_from_table, '%Y-%m-%d %H:%M:%S') # converting string timestamp to a datetime object
time_difference = current_time_truncated - date_time_obj
result = time_difference.seconds # datetime.timedelta represented in seconds
assert result in range(1, 60), error()
It works just fine, but probably there is a shorter way to compare a difference between a timestamp saved as string and actual utc timestamp. Thanks for any advice.
I'm reading between the lines a bit, but it sounds like at a high level your goal is to calculate the elapsed seconds between two times. If I'm right about that, here is a typical way to do it in Python:
import datetime
import time
previous = datetime.datetime.now()
time.sleep(5) # Added to simulate the passing of time for demonstration purposes
current = datetime.datetime.now()
elapsed_seconds = (current - previous) / datetime.timedelta(seconds=1)
"Division" by timedelta is the key to getting elapsed seconds (or any other time unit) between two datetime objects. While not UTC specific hopefully this shines a light on an approach that works for you.

How to round a Unix/POSIX timestamp to the nearest 30-minutes?

I want to take an epoch that is returned from a SQL query and round up (or down) 30 minutes. I want to do this on the second line of code. Any idea how to do so?
s = row.get("values")[0][1]
s = <<<round to closest 30 mins>>>
t = datetime.fromtimestamp(float(s)/1000.)
dateFmt = "%Y-%m-%d"
timeFmt = "%H:%M"
date = t.strftime(dateFmt)
time = t.strftime(timeFmt)
First convert the data to your expected representation. This may involve timezone change. Assuming t is the representation you want, you can replace the elements you want:
# python 3
t.replace(minute=t.minute // 30 * 30, second=0, microsecond=0)
# python 2
t.replace(minute=t.minute / 30 * 30, second=0, microsecond=0)
I wouldn't use the solution from the comment about manipulating the timestamp itself, unless you're sure that it will always be in local timezone. You can run into issues with shifts by odd number of minutes (there are both +xx30 and +xx45 timezones)

When I substract two datetime object in python it is considering only time not taking day

I have two date time objects
`statrt_time` and `end_time`
my code is
if self.book_from and self.book_to:
fmt = '%Y-%m-%d %H:%M:%S'
s = datetime.strptime(self.book_from,fmt) #start date
e = datetime.strptime(self.book_to,fmt) #end date
diff = e - s
total_seconds=diff.seconds
time_diff = (total_seconds/3600.0)
no_of_units = (time_diff/4)
if(e<s):
self.units = 0
else:
self.units = math.ceil(no_of_units)
Here when I subtract time within the same day it is giving the correct difference. But when the day is changed, it is not calculating the day difference but only giving time difference. How can I add day difference also?
Use total_seconds() instead of seconds.
timedelta.seconds just shows "second" part of the difference, while total_seconds() shows the duration of the difference in seconds. See Mureinik's answer for more details.
So, use this:
total_seconds=diff.total_seconds()
total_seconds is a timedelta object which stores the difference between two datetimes using three fields - days, seconds and miliseconds. Your snippet just uses the seconds attributes instead of the entire difference. The total_seconds() method takes care of this for you and returns, well, the total number of seconds between two datatimes.
I got another way of doing.. BUT A WORK AROUND..
if self.book_from and self.book_to:
fmt = '%Y-%m-%d %H:%M:%S'
s = datetime.strptime(self.book_from,fmt) #start date
e = datetime.strptime(self.book_to,fmt) #end date
diff = e - s
days=diff.days// convert difference to day instead of seconds//
days_seconds=0
if(days>0): //Checking whether the difference exceeds a day//
days_seconds=days*24*3600 //If so convert it to seconds//
total_seconds=diff.seconds+days_seconds
time_diff = (total_seconds/3600.0)

Categories