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
Related
I have the following code:
import datetime
from datetime import datetime as dt
def ceil_dt(dt, delta):
return dt + (dt.min - dt) % delta
NextInterval5m = ceil_dt(now, timedelta(minutes=5))
unixtime5m = dt.fromtimestamp(NextInterval5m)
The problem is that i keep getting the following error:
TypeError: an integer is required (got type datetime.datetime)
Can someone help me out on this? I don't understand to what i am supposed to convert NextInterval5m in order to make it work. I'm trying to convert NextInterval5m to an Unix timestamp
You should be able to convert it into a unix timestamp by using .timestamp() on a datetime.datetime object. However, this function is exclusive to Python 3. If you need something for python 2, you can use .total_seconds() which requires a datetime.time_delta object instead.
Documentation: https://docs.python.org/3.8/library/datetime.html#datetime.datetime.timestamp
If you are using python 3.3+, use .timestamp()
import datetime
from datetime import datetime as dt
from datetime import timedelta
def ceil_dt(dt, delta):
return dt + (dt.min - dt) % delta
now = dt.now()
NextInterval5m = ceil_dt(now, timedelta(minutes=5))
unixtime5m = NextInterval5m.timestamp()
print(unixtime5m)
Output:
1596926400.0
OR
import datetime
from datetime import datetime as dt
from datetime import timedelta
def ceil_dt(dt, delta):
return dt + (dt.min - dt) % delta
now = dt.now()
NextInterval5m = ceil_dt(now, timedelta(minutes=5))
unixtime5m = NextInterval5m.timestamp()
print((NextInterval5m - datetime.datetime(1970,1,1)).total_seconds())
from datetime import datetime as dt
fmt = '%a %d %b %Y %H:%M:%S %z'
for i in range(int(input())):
print(int(abs((dt.strptime(input(), fmt) -
dt.strptime(input(), fmt)).total_seconds())))
Why are we able to call the total_seconds() method without importing the timedelta class? As total_seconds() is a method in timedelta class.
When you subtract 2 datetime objects, the result is timedelta object.
from datetime import datetime
dt1 = datetime.now()
dt2 = datetime.now()
value = dt2 - dt1
print(type(value))
Output is:
<class 'datetime.timedelta'>
You are right, as you are subtracting two datetime objects. As per the method __sub__ it returns timedelta object (See below). And as you said total_seconds is method of timedelta class.
def __sub__(self, other):
"Subtract two datetimes, or a datetime and a timedelta."
if not isinstance(other, datetime):
if isinstance(other, timedelta):
return self + -other
return NotImplemented
days1 = self.toordinal()
days2 = other.toordinal()
secs1 = self._second + self._minute * 60 + self._hour * 3600
secs2 = other._second + other._minute * 60 + other._hour * 3600
base = timedelta(days1 - days2,
secs1 - secs2,
self._microsecond - other._microsecond)
if self._tzinfo is other._tzinfo:
return base
myoff = self.utcoffset()
otoff = other.utcoffset()
if myoff == otoff:
return base
if myoff is None or otoff is None:
raise TypeError("cannot mix naive and timezone-aware time")
return base + otoff - myoff
The import machinery works at 2 levels. First it loads and execute the module. So if it contains other imports, they are loaded (and executed) too. That means that the instruction
from datetime import datetime as dt
actually loads datetime (to be able to access datetime.datetime), and datetime.datetime. Because of that, datetime.timedelta is loaded too. In fact, it is required from datetime.datetime to be able to define the difference between 2 datetime.datetime objects. So everything has been loaded by the Python interpretor.
The second level imports symbols in the current namespace. At this level,
from datetime import datetime as dt
only creates the dt symbol in the namespace. That means that if you use directly datetime in your code, you will get a NameError because the symbol is undefined, but if you examine sys.module, you will find that it is there...
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)
As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday
I need to convert a datetime object with microsecond resolution to a timestamp, the problem is that I don't get the same timestamp second's resolution.
For example the timestamp that I pass as an argument is 1424440192 and I get in return 1424429392.011750, why is this?, I Only changed microsecond value of the datetime object, so I expect to change only values after the dot.
PD: In this example I'm only simulating one timestamp.
from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
td = dt - epoch
return td.total_seconds()
#return (td.microseconds + (td.seconds + td.days * 24 * 3600) *
#10**6) / 1e6
timestamp_pc = 1424440192
tm = datetime.fromtimestamp(timestamp_pc)
new_tm = tm.replace(microsecond = 11750)
print tm
print new_tm
print timestamp_pc
print "%f " %(totimestamp(new_tm))
I get it.
I changed
tm = datetime.fromtimestamp(timestamp_pc)
for
tm = datetime.utcfromtimestamp(timestamp_pc)
and now timestamp are identical.
From the fromtimestamp documentation:
If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.
Since your totimestamp function does not do the same timezone adjustment in reverse, the time is wrong by your time zone offset.