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
2D List Has Weird Behavor When Trying to Modify a Single Value
How to Find Out If Python Is Compiled with Ucs-2 or Ucs-4
What Is the Pythonic Way to Unpack Tuples
Encode and Assemble Multiple Features in Pyspark
Check If All Elements of a List Are of the Same Type
Dlib Installation on Windows 10
Check If a Number Is Odd or Even in Python
How to Implement a Pythonic Equivalent of Tail -F
Selenium: Firefoxprofile Exception Can't Load the Profile
Python Lookup Hostname from Ip with 1 Second Timeout
How to Modify Variable in Python That Is in Outer, But Not Global, Scope
How to Suppress the Newline After a Print Statement
Function with Varying Number of for Loops (Python)
Typeerror: Worker() Takes 0 Positional Arguments But 1 Was Given
Non-Ascii Characters in Matplotlib
Plot Pandas Dataframe as Bar and Line on the Same One Chart
Multiprocessing.Pool: What's the Difference Between Map_Async and Imap