How can I truncate milliseconds to 2 most significant decimals in strftime() - python

I have a datetime object that is printed with:
from datetime import datetime
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").strip()
print('TS: {}'.format(ts))
# "2020-12-03 02:13:27.823467"
However, I only want the first 2 digits of the milliseconds to be shown, like this: 2020-12-03 02:13:27.82. Using "%.2f" didn't work, and perhaps there's another time function more suitable?
What is the best way to do this without introducing (possibly laggy) regex string manipulations?

What about something like the following?
import datetime
now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d %H:%M:%S') + '.{:02d}'.format(round(now.microsecond, -4))[:3]
print('TS: {}'.format(ts))
# TS: 2020-12-03 01:22:01.86
EDIT
Perhaps a better parametrized solution would be:
import datetime
def largest_digits(value, num_digits=2, max_digits=6):
discard_digits = num_digits - max_digits
base = 10 ** -discard_digits
return f'{round(value, discard_digits) // base:02d}'
now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d %H:%M:%S') + '.' + largest_digits(now.microsecond, 2)
print('TS: {}'.format(ts))
# TS: 2020-12-03 01:22:01.86

Aaahi, the answer was trivial! Use string selection.
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").strip()[:-4]

Related

How to subtract 2 hours from time formatted as string [duplicate]

This question already has answers here:
Subtract hours and minutes from time
(3 answers)
Closed last year.
My initial string looks like following:
a1 = "06:00:00"
a2 = "01:00:00"
I want to set the time back by two hours.
How to get the following output (in string format)?
a1_new = "04:00:00"
a2_new = "23:00:00"
Here you go!
from datetime import datetime, timedelta
a1 = "06:00:00"
x = datetime.strptime(a1, "%H:%M:%S") - timedelta(hours=2, minutes=0)
y = x.strftime("%H:%M:%S")
print(y)
Steps:
Convert HMS into a DateTime Object
Minus 2 hours from this
Convert the result into a String that only contains Hour Minute & Second
from datetime import datetime
from datetime import timedelta
time_fmt = "%H:%M:%S"
a1_new = datetime.strptime(a1, time_fmt) - timedelta(hours = 2)
a1_new = a1_new.strftime("%H:%M:%S")
print(a1_new)
'08:00:00'
I am assuming here that you only need a simple 24-hour clock.
s = "01:00:00"
h, m, s = s.split(":")
new_hours = (int(h) - 2) % 24
result = ':'.join((str(new_hours).zfill(2), m, s))
convert to datetime:
import datetime
a1 = "06:00:00"
obj = datetime.datetime.strptime(a1,"%H:%M:%S")
obj.replace(hour=obj.hour-2) #hours = hours - 2
tostr = obj.hour+":"+obj.min+":"+obj.second
print(tostr)
If your strings are always going to follow that exact format and you don't want to use datetime, here's a different way to do it: You could split the strings by their colons to isolate the hours, then work on them that way before joining back to a string.
a1 = "06:00:00"
parts = a1.split(":") # split by colons
hour = (int(parts[0]) - 2) % 24 # isolate hour, convert to int, and subtract hours, and clamp to our 0-23 bounds
parts[0] = f"{hour:02}" # :02 in an f-string specifies that you want to zero-pad that string up to a maximum of 2 characters
a1_new = ":".join(parts) # rejoin string to get new time
If there's any uncertainty in the format of the string however, this completely falls apart.
Convert to datetime, subtract timedelta, convert to string.
from datetime import datetime, timedelta
olds = ["06:00:00", "01:00:00"]
objs = [datetime.strptime(t, "%H:%M:%S") - timedelta(hours=2) for t in olds]
news = [t.strftime("%H:%M:%S") for t in objs]
You can use datetime and benefit from the parameters of datetime.timedelta:
from datetime import datetime, timedelta
def subtime(t, **kwargs):
return (datetime.strptime(t, "%H:%M:%S") # convert to datetime
- timedelta(**kwargs) # subtract parameters passed to function
).strftime("%H:%M:%S") # format as text again
subtime('01:00:00', hours=2)
# '23:00:00'
subtime('01:00:00', hours=2, minutes=62)
# '21:58:00'

python datetime with 6 digit milliseconds

How could I print 6 digit milli seconds in below format
>>> import datetime
>>> datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='milliseconds')
'2022-01-10T18:29:10.698000+05:30'
Actual Output:
'2022-01-10T18:29:10.108+05:30'
Expecting Output something like:
'2022-01-10T18:29:10.108000+05:30'
Use timespec=microseconds:
>>> dt = datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='microseconds')
'2022-01-10T14:05:55.742931+01:00'
Update:
If you want 0 for microsecond value, you can do:
now = datetime.datetime.now().astimezone()
now = now.replace(microsecond=now.microsecond // 1000 * 1000)
now = now.isoformat(timespec='microseconds')
print(now)
# Output
'2022-01-10T14:17:08.386000+01:00'
There are only 1000ms in 1 second, do you mean microseconds?
datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='microseconds')
If you want utc and milliseconds value, you can do
UTC Convertion
import pytz
from datetime import datetime
epoch: datetime = datetime.now().replace(tzinfo=pytz.utc)
print(epoch)

How to add times that has HH:MM:SS,XX format in python

My expertise lack when it comes to understanding this time format. I am guessing the ,XXX is XXX/1000 of a second?
Nevertheless I am trying to add a text files that contains time stamp like these and sum up the total.
Below is an example,
00:03:33,950
00:03:34,590
This is what I have so far but I'm not sure how to add up the last part
Hours = s.split(":")[0]
Minutes = s.split(":")[1]
Seconds = (s.split(":")[2]).split(",")[0]
Total_seconds = (Hours * 3600) + (Minutes * 60) + (Seconds)
Total_Time = str(datetime.timedelta(seconds=Total_seconds))
Reed this documentation about time.strftime() format
For example
from time import gmtime, strftime
strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
--'Thu, 28 Jun 2001 14:17:15 +0000'--
Actually, you're halfway there.
All you have to do is to to convert your strs into int and pass them as parameters to the appropriate timedelta keywords.
from datetime import timedelta
Hours = int(s.split(":")[0])
Minutes = int(s.split(":")[1])
Seconds = int((s.split(":")[2]).split(",")[0])
Milliseconds = int((s.split(":")[2]).split(",")[1])
duration = timedelta(hours=Hours, minutes=Minutes, seconds=Seconds, milliseconds=Milliseconds)
After adding all the durations you need, str() the final timedelta object.
>>> durations_1 = timedelta(hours=2,milliseconds=750)
>>> durations_2 = timedelta(milliseconds=251)
>>> durations_sum = durations_1 + durations_2
>>> str(durations_sum)
'2:00:01.001000'
>>> str(durations_sum).replace('.',',')
'2:00:01,001000'

How do I convert a Simple Integer to a time's Minutes

I have this integers here i = 33 and o = 156, what i want to do is to convert these integers into minutes in a time format to become these results:
i => 00:33:00
o => 02:36:00
i tried this:
from datetime import datetime, timedelta
i = 33
o = 156
itime = datetime.timedelta(minutes=i)
itime = datetime.timedelta(minutes=o)
and it gives me this error
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
which is solved by adding import datetime
but in my code it breaks some parts of it like datetime.strptime() when i add it like this
import datetime
from datetime import datetime, timedelta
also i tried without the from datetime import datetime, timedelta like this datetime.timedelta(minutes=33) but the result was
datetime.timedelta(0, 1980)
but i want it to be by minutes and not seconds like this datetime.time(0, 33)
Amend the above code to this:
from datetime import datetime, timedelta
i = 33
o = 156
itime = timedelta(minutes=i)
itime = timedelta(minutes=o)
You already imported timedelta, so you do not need to call it as a child library from datetime. The additional datetime import overrides the child library import.
Not sure why you use itime twice though it would override the first one as well...
You should be able to do
x = datetime.time(0,0) + timedelta(minutes=i)
Give this a try
def convert_to_minutes(i):
hr = i // 60
m = i - hr * 60
res_ = str(hr) + ":" + str(m) + ":" + "00"
res = datetime.strptime(res_, '%H:%M:%S').time()
return res

add 2 hours in current time in Python and print the time in timestamp

How to get the current time and return that in timestamp format after adding 2 hours in it like 1535020200000
i tried the following but I am not getting the expected result
current_time + timedelta(hours=2)
(datetime.now()).split('.')[0] + timedelta(hours=2)
since the second one returns a string, addition operation cannot be done
I would recommend the following
from datetime import datetime, timedelta
two_hours_from_now = datetime.now() + timedelta(hours=2)
print(two_hours_from_now.timestamp())
You can do as follow:
import datetime
current_time = datetime.datetime.now()
later = current_time + datetime.timedelta(hours=2)
print(later.timestamp())
You get:
1535031690.031316
Quoting the documentation:
Return POSIX timestamp corresponding to the datetime instance. The return value is a float similar to that returned by time.time().
If you need a timestamp, use time.time:
current_plus_2_hours = time.time() + 2 * 60 * 60
thanks to all of you, though this worked for me
start_at = 2
hours_from_now = int(str(time.time() + start_at * 60 * 60)[0:10]) * 1000

Categories