I need to add a given number of minutes or seconds to a Time object that comes without the date portion.
For Ex:
Time: 13:00:00 + 10 minutes (Should return 13:10:00)
Time: 21:50:00 + 1800 seconds (Should return 22:20:00)
My code:
from datetime import timedelta
d = timedelta(minutes=30)
calendar_entry + d #calendar_entry is a time object HH:MM:SS
Error:
During handling of the above exception (unsupported operand type(s)
for +: 'datetime.time' and 'datetime.timedelta'), another exception
occurred:
How can I do this in Python 3?
Try this:
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(13, 0)) + timedelta(minutes=10)
print (dt.time())
#13:10:00
Here's what you want:
import datetime
date = datetime.datetime.strptime('15:57:12', '%H:%M:%S')
print(date.strftime('%H:%M:%S'))
date = date+datetime.timedelta(seconds=1800)
print(date.strftime('%H:%M:%S'))
date = date+datetime.timedelta(minutes=30)
print(date.strftime('%H:%M:%S'))
Output:
15:57:12
16:27:12
16:57:12
This way of manipulation is only possible with datetime objects, but luckily, you can do the conversion from datetime to time, to have it your way. Take a look at add_minutes:
import datetime
def add_minutes(tm, minutes1):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(minutes=minutes1)
return fulldate.time()
a = datetime.datetime.now().time()
b = add_minutes(a, 2)
print(a)
print(b)
Related
i want to calculate difference in seconds, between two dates.
def delta_seconds(datetime, origin):
td = datetime - origin # datetime - date
return float((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6)) / 10 ** 6
I can't compute the difference and it shows me this error:
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.datetime
So, i want to convert datetime.time into datetime.datetime.
(datetime is a datetime.time obj and origin is a datetime.datetime obj)
Any suggestion?
Never perform calculations yourself when you can get the desired things from the standard library. The difference between two datetime.datetime objects gives you datetime.timedelta which already has a class attribute, seconds which you can return from your function.
You can use datetime.combine to combine datetime.date and datetime.time.
Demo:
from datetime import datetime, date, time
def delta_seconds(end, origin):
return (end - origin).seconds
# Test
date = date(2021, 5, 3)
time = time(10, 20, 30)
origin = datetime.combine(date, time)
end = datetime.now()
print(delta_seconds(end, origin))
Output:
33213
The subtraction of two different datetime already returns a delta. timedelta
The params origin and datetime have to be a datetime object. Either make both params to a datetime object or the object that is datetime.time to an current datetime` object.
For converting your time to datetime, this may help or you adjust the fields manually.
import datetime
t = datetime.time(1, 2, 3)
print('t :', t)
d = datetime.date.today()
print('d :', d)
dt = datetime.datetime.combine(d, t)
print('dt:', dt)
output
t : 01:02:03
d : 2013-02-21
dt: 2013-02-21 01:02:03
Below is the sample code I am using inside my one of the application. I want Default hour format as 00 (e.g. 02:30:35) and here I am getting as 0:00:03.011445 so I am using strftime but I am getting another exception there. Please guide on it.
from datetime import datetime
from datetime import time
from time import strftime
import time
start = datetime.now()
time.sleep(3)
end = datetime.now()
print(start)
print(end)
dt = (end - start)
print('Defual Time:', dt)
print('New Format DateTime', dt.strftime("%m/%d/%y %H:%M:%S"))
I am getting below output.
2020-10-17 19:15:36.831928
2020-10-17 19:15:39.843373
Defualt Time: 0:00:03.011445
Traceback (most recent call last):
File "D:/New folder/IoT2.py", line 30, in <module>
print('New Format DateTime', dt.strftime("%m/%d/%y %H:%M:%S"))
AttributeError: 'datetime.timedelta' object has no attribute 'strftime'
The reason why you are getting the Attribute Error is because strftime belongs to datetime.datetime class ( from datetime.now()) and not datetime.timedelta class (from end-start).
Instead, you can actually use total_seconds() method to fetch the seconds of the time difference and format it in string however you wish.
Edit: You can use microseconds attribute of timedelta to calculate your milliseconds and format it to display.
from datetime import datetime
from datetime import time
from time import strftime
import time
start = datetime.now()
time.sleep(3)
end = datetime.now()
print(start)
print(end)
dt = (end - start)
print('Default Time:', dt)
milliseconds = int(round(dt.microseconds/1000, 1))
dt = int(dt.total_seconds())
print('New format: {:02}:{:02}:{:02}:{:03}'.format(dt // 3600, dt % 3600 // 60, dt % 60, milliseconds))
The output for this would be:
2020-10-19 13:02:13.861103
2020-10-19 13:02:16.863268
Default Time: 0:00:03.002165
New format: 00:00:03:002
u can just get seconds and days from a datetime.timedelta so u can do something like this!
from datetime import datetime
import time
start = datetime.now()
time.sleep(3)
end = datetime.now()
print(start)
print(end)
dt = (end - start)
print('Default Time:', dt)
def days_hours_minutes(td):
x = (td.days, td.seconds//3600, (td.seconds//60)%60, td.seconds)
return x #(days, hrs, mins, seconds)
print('New Format DateTime', days_hours_minutes(dt))
You can use the method total_seconds of the timedelta object and calculate the respective hours minutes and second by yourself and then you can format the output string as you want.
from datetime import datetime
from datetime import time
from time import strftime
import time
start = datetime.now()
time.sleep(3)
end = datetime.now()
print(start)
print(end)
dt = (end - start)
print('Defual Time:', dt)
dt_sec=dt.total_seconds()
hours,rem=divmod(dt_sec,3600)
minutes,rem=divmod(rem,60)
print('New Format DateTime', f'{hours:0>2.0f}:{minutes:0>2.0f}:{rem:0>2.0f}:'+f'{rem:.3f}'[-3:])
Edit
I added also the printing of the milliseconds.
I want to add particular time in present date.
e.g. 2020-10-22 12:00:00.
For that I have tried in the following way
from datetime import datetime, timedelta, date
duration = "12:00:00"
duration_obj = datetime.strptime(duration, '%H:%M:%S')
Date_Time = date.today() + duration_obj
But , I'm gettimg an error
TypeError: unsupported operand type(s) for +: 'datetime.date' and 'datetime.datetime'
Any suggestion will be helpful....
You can convert 12:00:00 to datetime.time object using fromisoformat, convert that to seconds and add it to the actual time:
from datetime import datetime, timedelta, date, time
duration = "12:00:00"
duration_obj = time.fromisoformat(duration)
total_seconds = duration_obj.second + duration_obj.minute*60 + duration_obj.hour*3600
Date_Time = datetime.now() + timedelta(seconds=total_seconds)
print(datetime.now())
print(Date_Time)
Out:
2020-10-22 17:30:15.878372
2020-10-23 05:30:15.878357
Edit (using datetime.combine):
from datetime import datetime, timedelta, date, time
duration = "12:00:00"
duration_obj = time(*(int(x) for x in duration.split(':')))
Date_Time = datetime.combine(date.today(), duration_obj)
print(Date_Time)
>>>2020-10-22 12:00:00
Construct the datetime object directly:
duration = "12:00:00"
_today = date.today()
datetimeList = [_today.year, _today.month, _today.day] + [int(x) for x in duration.split(':')]
Date_Time = datetime(*datetimeList)
print(Date_Time)
>>> 2020-10-22 12:00:00
Transform them into string before concatenation:
separator = " | "
date_time = str(date.today()) + separator + duration
The error is telling you that those operands: datetime.date and datetime.datetime object are not valid for + concatenation operation.
I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch.
How do I do this?
It appears to me that the simplest way to do this is
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
In Python 3.3, added new method timestamp:
import datetime
seconds_since_epoch = datetime.datetime.now().timestamp()
Your question stated that you needed milliseconds, which you can get like this:
milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000
If you use timestamp on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
time.mktime
datetime.timetuple
You can use Delorean to travel in space and time!
import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch
http://delorean.readthedocs.org/en/latest/quickstart.html
This is how I do it:
from datetime import datetime
from time import mktime
dt = datetime.now()
sec_since_epoch = mktime(dt.timetuple()) + dt.microsecond/1000000.0
millis_since_epoch = sec_since_epoch * 1000
Recommendedations from the Python 2.7 docs for the time module
from datetime import datetime
from calendar import timegm
# Note: if you pass in a naive dttm object it's assumed to already be in UTC
def unix_time(dttm=None):
if dttm is None:
dttm = datetime.utcnow()
return timegm(dttm.utctimetuple())
print "Unix time now: %d" % unix_time()
print "Unix timestamp from an existing dttm: %d" % unix_time(datetime(2014, 12, 30, 12, 0))
Here's another form of a solution with normalization of your time object:
def to_unix_time(timestamp):
epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
my_time = datetime.datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S.%f") # plugin your time object
delta = my_time - epoch
return delta.total_seconds() * 1000.0
>>> import datetime
>>> import time
>>> import calendar
>>> #your datetime object
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 3, 19, 13, 0, 9, 351812)
>>> #use datetime module's timetuple method to get a `time.struct_time` object.[1]
>>> tt = datetime.datetime.timetuple(now)
>>> tt
time.struct_time(tm_year=2013, tm_mon=3, tm_mday=19, tm_hour=13, tm_min=0, tm_sec=9, tm_wday=1, tm_yday=78, tm_isdst=-1)
>>> #If your datetime object is in utc you do this way. [2](see the first table on docs)
>>> sec_epoch_utc = calendar.timegm(tt) * 1000
>>> sec_epoch_utc
1363698009
>>> #If your datetime object is in local timeformat you do this way
>>> sec_epoch_loc = time.mktime(tt) * 1000
>>> sec_epoch_loc
1363678209.0
[1] http://docs.python.org/2/library/datetime.html#datetime.date.timetuple
[2] http://docs.python.org/2/library/time.html
A bit of pandas code:
import pandas
def to_millis(dt):
return int(pandas.to_datetime(dt).value / 1000000)
import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000
A lot of these answers don't work for python 2 or don't preserve the milliseconds from the datetime. This works for me
def datetime_to_ms_epoch(dt):
microseconds = time.mktime(dt.timetuple()) * 1000000 + dt.microsecond
return int(round(microseconds / float(1000)))
Here is a function I made based on the answer above
def getDateToEpoch(myDateTime):
res = (datetime.datetime(myDateTime.year,myDateTime.month,myDateTime.day,myDateTime.hour,myDateTime.minute,myDateTime.second) - datetime.datetime(1970,1,1)).total_seconds()
return res
You can wrap the returned value like this : str(int(res))
To return it without a decimal value to be used as string or just int (without the str)
This other solution for covert datetime to unixtimestampmillis.
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
DateTime localDateTime, univDateTime;
localDateTime = DateTime.Now;
univDateTime = localDateTime.ToUniversalTime();
return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
}
from datetime import datetime, date, time
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.now
time.sleep(5)
d2 = datetime.now
diff = (d2-d1).seconds
print(diff)
i get the error message with
diff = (d2-d1).seconds
TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'builtin_function_or_method'
how to different the two datetime in seconds format?
You are missing your brackets () after now:
from datetime import datetime, date, time
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.now()
time.sleep(5)
d2 = datetime.now()
diff = (d2-d1).seconds
print(diff)
now is a function, so what you are trying to subtract are two functions. Try this:
datetime.now() - datetime.now()
The problem is that you are not calling the datetime.now function, you are merely assigning d1 and d2 to the reference of the function. This should solve your problem:
d1 = datetime.now() # note the function call
d2 = datetime.now()