Can't Subtract Offset-Naive and Offset-Aware Datetimes

Can't subtract offset-naive and offset-aware datetimes

have you tried to remove the timezone awareness?

from http://pytz.sourceforge.net/

naive = dt.replace(tzinfo=None)

may have to add time zone conversion as well.

edit: Please be aware the age of this answer. An answer involving ADDing the timezone info instead of removing it in python 3 is below. https://stackoverflow.com/a/25662061/93380

Datetime and suntime, TypeError: can't subtract offset-naive and offset-aware datetimes

I'd suggest you also localize TO, so that you have all tz-aware datetime objects. You can easily localize a datetime object to the local timezone by calling the astimezone() method with no timezone specified. I also took the freedom to simplify the code a bit:

from datetime import datetime, timedelta
from suntime import Sun

lat, long, TO_date, TO_time = 49.095, 8.437, '2020-06-24', '10:45:00.000000'

sun = Sun(lat, long)

# making use of input in ISO8601 compatible format,
# and localize to the local timezone:
TO = datetime.fromisoformat(TO_date + 'T' + TO_time).astimezone()

day_sr = sun.get_local_sunrise_time(TO) # 2020-06-24 05:23:00+02:00
day_ss = sun.get_local_sunset_time(TO) # 2020-06-24 21:35:00+02:00

n_end = day_sr - timedelta(minutes=30)
n_start = day_ss + timedelta(minutes=30)

print(TO)
print(n_end)
print(TO-n_end)

# 2020-06-24 10:45:00+02:00
# 2020-06-24 04:53:00+02:00
# 5:52:00

Note that I also adjusted lat/lon so I can verify the result for my location/timezone. As +02:00 indicates, I'm on UTC+2 (CEST).


The other option, if you want to work with all-naive datetime objects, is to replace the tzinfo property with None. In the code above that would look like

TO = datetime.fromisoformat(TO_date + 'T' + TO_time) # 2020-06-24 10:45:00
day_sr = sun.get_local_sunrise_time(TO).replace(tzinfo=None) # 2020-06-24 05:23:00
day_ss = sun.get_local_sunset_time(TO).replace(tzinfo=None) # 2020-06-24 21:35:00

This is also fine since you only work with local times anyway.

Django: can't subtract offset-naive and offset-aware datetimes

Just use timezone aware time for your calculation:

from django.utils.timezone import localdate

class CustomUser(AbstractUser):

def free_trial(self):
if (self.date_joined - localdate()) < timedelta(days=7):
return True

can't subtract offset-naive and offset-aware datetimes when I try to export to excel

The right way to do this is is to add values_list = [[x.strftime("%Y-%m-%d %H:%M") if isinstance(x, datetime.datetime) else x for x in row] for row in values_list]

In the view to be like :

def export_warehouse_movement_report_csv(request):
today_date = date.today()
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="warehouse_movement_' + str(today_date) + '.xls"'
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('BuyAndSells')
# Sheet header, first row
row_num = 0
font_style = xlwt.XFStyle()
font_style.font.bold = True
columns = ['المستخدم', 'الكمية', 'الكتاب', 'الصنف', 'الفئة', 'نوع الحركة', 'التاريخ']
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style)
# Sheet body, remaining rows
font_style = xlwt.XFStyle()
rows = models.WarehouseMovement.objects.all().values_list('user', 'item_quantity', 'book_name', 'item_name',
'move_class', 'move_type', 'date')
rows = [[x.strftime("%Y-%m-%d %H:%M") if isinstance(x, datetime.datetime) else x for x in row] for row in rows ]
for row in rows:
row_num += 1
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
wb.save(response)
return response

Python can't subtract offset-naive and offset-aware datetimes

If you have a datetime object you can get the seconds from the epoch from it directly:

d = datetime.datetime(2015,1,1)
print int(d.strftime("%s"))

In your question, .601681 is extra resolution in the time, in microseconds,
and +00:00 is the offset in hours:minutes from UTC (previously GMT).

TypeError: can't subtract offset-naive and offset-aware datetimes

Fixed it by changing the print to

print datetime.utcnow().replace(tzinfo=pytz.UTC)-last

Comparing two Python 3 datetime objects returns can't compare offset-naive and offset-aware datetimes: TypeError

The main problem is that I'm assuming launchTime is timezone aware, whereas datetime.now() is not (datetime.now().tzinfo == None).

There are a couple ways to solve this, but the easiest would be to remove the tzinfo from launchTime: if launchTime.replace(tzinfo=None) < datetime.datetime.now()-datetime.timedelta(seconds=20) should do the trick.

Alternatively, you can convert your datetime objects to Unix timestamps and then you don't have to deal with timezone silliness.



Related Topics



Leave a reply



Submit