Experiencing odd output from django.utils.timezone.now(), datetime.datetime.now() and pytz.timezoneHow to return only the Date from a SQL Server DateTime datatypeHow to flush output of print function?Php Daylight saving issue with Pacific/FijiHow can I get the timezone-aware year, month, day, hour etc. from a Python datetime?How can I convert date and time to timestamp by giving/considering timezone?Difference between dates in Python and print as 00:00:00How can I write an ISO 8601 date with a timezone but no time componentRetrieving timezone in pretty formatted git log output (format specifier)?How to deal with time zone changes in Django?

What is the name of the technique when an element is repeated at different scales?

Is it bad to suddenly introduce another element to your fantasy world a good ways into the story?

Minimizing medical costs with HSA

What do you call the angle of the direction of an airplane?

Machine Learning Golf: Multiplication

Advice for making/keeping shredded chicken moist?

How to calculate a conditional PDF in mathematica?

How can solar sailed ships be protected from space debris?

Will electrically joined dipoles of different lengths, at right angles, behave as a multiband antenna?

Is it possible that Curiosity measured its own methane or failed doing the spectrometry?

How do both sides know the MTU

Using Sed to add counter to keyword

Was Wolfgang Unzicker the last Amateur GM?

Milky way is orbiting around?

How did שְׁלֹמֹה (shlomo) become Solomon?

Convenience stores in India

What's the big deal about the Nazgûl losing their horses?

How did Einstein know the speed of light was constant?

Is there a typical layout to blocking installed for backing in new construction framing?

Should I hide my travel history to the UK when I apply for an Australian visa?

How to supply water to a coastal desert town with no rain and no freshwater aquifers?

How to deal with administrative duties killing the research spirit?

Are there advantages in writing by hand over typing out a story?

What instances can be solved today by modern solvers (pure LP)?



Experiencing odd output from django.utils.timezone.now(), datetime.datetime.now() and pytz.timezone


How to return only the Date from a SQL Server DateTime datatypeHow to flush output of print function?Php Daylight saving issue with Pacific/FijiHow can I get the timezone-aware year, month, day, hour etc. from a Python datetime?How can I convert date and time to timestamp by giving/considering timezone?Difference between dates in Python and print as 00:00:00How can I write an ISO 8601 date with a timezone but no time componentRetrieving timezone in pretty formatted git log output (format specifier)?How to deal with time zone changes in Django?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm experiencing strange behavior when attempting to convert between UTC and specific timezones. I'd love for someone to explain why I'm seeing this behavior and what the more "correct" way of getting timezone information might be.



Code:



import pytz
import datetime
from django.utils import timezone

print(timezone.now())
print(pytz.utc.localize(datetime.datetime.now()))
print('n')

def get_local_and_utc_date_ranges(days=1500, days_ago=2, local_timezone="America/Asuncion"):
seller_timezone = pytz.timezone(local_timezone)
utc_timezone = pytz.utc

seller_today = timezone.now().astimezone(seller_timezone)
seller_days_ago = seller_today - timezone.timedelta(days=days_ago)

local_date_end = seller_days_ago.replace(hour=23, minute=59, second=59, microsecond=999999)
local_date_start = (local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)

utc_date_end = local_date_end.astimezone(utc_timezone)
utc_date_start = local_date_start.astimezone(utc_timezone)

date_ranges =
"local_date_end": local_date_end,
"local_date_start": local_date_start,
"utc_date_end": utc_date_end,
"utc_date_start": utc_date_start,


return date_ranges


def get_utc_and_local_date_ranges(days=1500, days_ago=2, local_timezone='America/Asuncion'):
seller_timezone = pytz.timezone(local_timezone)
utc_timezone = pytz.utc

utc_today = datetime.datetime.utcnow()
utc_days_ago = utc_today - datetime.timedelta(days=days_ago)

local_date_end = seller_timezone.localize(utc_days_ago).replace(
hour=23, minute=59, second=59, microsecond=999999
)
local_date_start = (local_date_end - datetime.timedelta(days=days)).replace(
hour=0, minute=0, second=0, microsecond=0
)
utc_date_end = local_date_end.astimezone(utc_timezone)
utc_date_start = local_date_start.astimezone(utc_timezone)

date_ranges =
'local_date_end': local_date_end,
'local_date_start': local_date_start,
'utc_date_end': utc_date_end,
'utc_date_start': utc_date_start,


return date_ranges



days = 1500
days_ago = 2

dates = get_local_and_utc_date_ranges(days=days, days_ago=days_ago)
dates2 = get_utc_and_local_date_ranges(days=days, days_ago=days_ago)


print('dates1:')
print('local_date_start:', dates['local_date_start'])
print('local_date_end:', dates['local_date_end'])
print('utc_date_start:', dates['utc_date_start'])
print('utc_date_end:', dates['utc_date_end'])
print('n')

print('dates2:')
print('local_date_start:', dates2['local_date_start'])
print('local_date_end:', dates2['local_date_end'])
print('utc_date_start:', dates2['utc_date_start'])
print('utc_date_end:', dates2['utc_date_end'])
print('n')


Output:



2019-03-25 18:57:55.929908+00:00
2019-03-25 18:57:55.930005+00:00


dates1:
local_date_start: 2015-02-12 00:00:00-04:00
local_date_end: 2019-03-23 23:59:59.999999-04:00
utc_date_start: 2015-02-12 04:00:00+00:00
utc_date_end: 2019-03-24 03:59:59.999999+00:00


dates2:
local_date_start: 2015-02-12 00:00:00-03:00
local_date_end: 2019-03-23 23:59:59.999999-03:00
utc_date_start: 2015-02-12 03:00:00+00:00
utc_date_end: 2019-03-24 02:59:59.999999+00:00


Note the inconsistent UTC offset (that particular timezone switched to DST on Mar 23rd). But when I try to replicate the issue using the following code:



import pytz 
import datetime
from django.utils import timezone

now1 = timezone.now() - datetime.timedelta(days=2)
now2 = pytz.utc.localize(datetime.datetime.now()) - datetime.timedelta(days=2)

seller_timezone = pytz.timezone('America/Asuncion')

print(now1.astimezone(seller_timezone).replace(
hour=23, minute=59, second=59, microsecond=999999
))
print(now2.astimezone(seller_timezone).replace(
hour=23, minute=59, second=59, microsecond=999999
))


The output is correct:



2019-03-23 23:59:59.999999-03:00
2019-03-23 23:59:59.999999-03:00


I'm hoping someone can understand why this behavior is happening and how I might avoid the inconsistencies if so.










share|improve this question






























    0















    I'm experiencing strange behavior when attempting to convert between UTC and specific timezones. I'd love for someone to explain why I'm seeing this behavior and what the more "correct" way of getting timezone information might be.



    Code:



    import pytz
    import datetime
    from django.utils import timezone

    print(timezone.now())
    print(pytz.utc.localize(datetime.datetime.now()))
    print('n')

    def get_local_and_utc_date_ranges(days=1500, days_ago=2, local_timezone="America/Asuncion"):
    seller_timezone = pytz.timezone(local_timezone)
    utc_timezone = pytz.utc

    seller_today = timezone.now().astimezone(seller_timezone)
    seller_days_ago = seller_today - timezone.timedelta(days=days_ago)

    local_date_end = seller_days_ago.replace(hour=23, minute=59, second=59, microsecond=999999)
    local_date_start = (local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)

    utc_date_end = local_date_end.astimezone(utc_timezone)
    utc_date_start = local_date_start.astimezone(utc_timezone)

    date_ranges =
    "local_date_end": local_date_end,
    "local_date_start": local_date_start,
    "utc_date_end": utc_date_end,
    "utc_date_start": utc_date_start,


    return date_ranges


    def get_utc_and_local_date_ranges(days=1500, days_ago=2, local_timezone='America/Asuncion'):
    seller_timezone = pytz.timezone(local_timezone)
    utc_timezone = pytz.utc

    utc_today = datetime.datetime.utcnow()
    utc_days_ago = utc_today - datetime.timedelta(days=days_ago)

    local_date_end = seller_timezone.localize(utc_days_ago).replace(
    hour=23, minute=59, second=59, microsecond=999999
    )
    local_date_start = (local_date_end - datetime.timedelta(days=days)).replace(
    hour=0, minute=0, second=0, microsecond=0
    )
    utc_date_end = local_date_end.astimezone(utc_timezone)
    utc_date_start = local_date_start.astimezone(utc_timezone)

    date_ranges =
    'local_date_end': local_date_end,
    'local_date_start': local_date_start,
    'utc_date_end': utc_date_end,
    'utc_date_start': utc_date_start,


    return date_ranges



    days = 1500
    days_ago = 2

    dates = get_local_and_utc_date_ranges(days=days, days_ago=days_ago)
    dates2 = get_utc_and_local_date_ranges(days=days, days_ago=days_ago)


    print('dates1:')
    print('local_date_start:', dates['local_date_start'])
    print('local_date_end:', dates['local_date_end'])
    print('utc_date_start:', dates['utc_date_start'])
    print('utc_date_end:', dates['utc_date_end'])
    print('n')

    print('dates2:')
    print('local_date_start:', dates2['local_date_start'])
    print('local_date_end:', dates2['local_date_end'])
    print('utc_date_start:', dates2['utc_date_start'])
    print('utc_date_end:', dates2['utc_date_end'])
    print('n')


    Output:



    2019-03-25 18:57:55.929908+00:00
    2019-03-25 18:57:55.930005+00:00


    dates1:
    local_date_start: 2015-02-12 00:00:00-04:00
    local_date_end: 2019-03-23 23:59:59.999999-04:00
    utc_date_start: 2015-02-12 04:00:00+00:00
    utc_date_end: 2019-03-24 03:59:59.999999+00:00


    dates2:
    local_date_start: 2015-02-12 00:00:00-03:00
    local_date_end: 2019-03-23 23:59:59.999999-03:00
    utc_date_start: 2015-02-12 03:00:00+00:00
    utc_date_end: 2019-03-24 02:59:59.999999+00:00


    Note the inconsistent UTC offset (that particular timezone switched to DST on Mar 23rd). But when I try to replicate the issue using the following code:



    import pytz 
    import datetime
    from django.utils import timezone

    now1 = timezone.now() - datetime.timedelta(days=2)
    now2 = pytz.utc.localize(datetime.datetime.now()) - datetime.timedelta(days=2)

    seller_timezone = pytz.timezone('America/Asuncion')

    print(now1.astimezone(seller_timezone).replace(
    hour=23, minute=59, second=59, microsecond=999999
    ))
    print(now2.astimezone(seller_timezone).replace(
    hour=23, minute=59, second=59, microsecond=999999
    ))


    The output is correct:



    2019-03-23 23:59:59.999999-03:00
    2019-03-23 23:59:59.999999-03:00


    I'm hoping someone can understand why this behavior is happening and how I might avoid the inconsistencies if so.










    share|improve this question


























      0












      0








      0








      I'm experiencing strange behavior when attempting to convert between UTC and specific timezones. I'd love for someone to explain why I'm seeing this behavior and what the more "correct" way of getting timezone information might be.



      Code:



      import pytz
      import datetime
      from django.utils import timezone

      print(timezone.now())
      print(pytz.utc.localize(datetime.datetime.now()))
      print('n')

      def get_local_and_utc_date_ranges(days=1500, days_ago=2, local_timezone="America/Asuncion"):
      seller_timezone = pytz.timezone(local_timezone)
      utc_timezone = pytz.utc

      seller_today = timezone.now().astimezone(seller_timezone)
      seller_days_ago = seller_today - timezone.timedelta(days=days_ago)

      local_date_end = seller_days_ago.replace(hour=23, minute=59, second=59, microsecond=999999)
      local_date_start = (local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)

      utc_date_end = local_date_end.astimezone(utc_timezone)
      utc_date_start = local_date_start.astimezone(utc_timezone)

      date_ranges =
      "local_date_end": local_date_end,
      "local_date_start": local_date_start,
      "utc_date_end": utc_date_end,
      "utc_date_start": utc_date_start,


      return date_ranges


      def get_utc_and_local_date_ranges(days=1500, days_ago=2, local_timezone='America/Asuncion'):
      seller_timezone = pytz.timezone(local_timezone)
      utc_timezone = pytz.utc

      utc_today = datetime.datetime.utcnow()
      utc_days_ago = utc_today - datetime.timedelta(days=days_ago)

      local_date_end = seller_timezone.localize(utc_days_ago).replace(
      hour=23, minute=59, second=59, microsecond=999999
      )
      local_date_start = (local_date_end - datetime.timedelta(days=days)).replace(
      hour=0, minute=0, second=0, microsecond=0
      )
      utc_date_end = local_date_end.astimezone(utc_timezone)
      utc_date_start = local_date_start.astimezone(utc_timezone)

      date_ranges =
      'local_date_end': local_date_end,
      'local_date_start': local_date_start,
      'utc_date_end': utc_date_end,
      'utc_date_start': utc_date_start,


      return date_ranges



      days = 1500
      days_ago = 2

      dates = get_local_and_utc_date_ranges(days=days, days_ago=days_ago)
      dates2 = get_utc_and_local_date_ranges(days=days, days_ago=days_ago)


      print('dates1:')
      print('local_date_start:', dates['local_date_start'])
      print('local_date_end:', dates['local_date_end'])
      print('utc_date_start:', dates['utc_date_start'])
      print('utc_date_end:', dates['utc_date_end'])
      print('n')

      print('dates2:')
      print('local_date_start:', dates2['local_date_start'])
      print('local_date_end:', dates2['local_date_end'])
      print('utc_date_start:', dates2['utc_date_start'])
      print('utc_date_end:', dates2['utc_date_end'])
      print('n')


      Output:



      2019-03-25 18:57:55.929908+00:00
      2019-03-25 18:57:55.930005+00:00


      dates1:
      local_date_start: 2015-02-12 00:00:00-04:00
      local_date_end: 2019-03-23 23:59:59.999999-04:00
      utc_date_start: 2015-02-12 04:00:00+00:00
      utc_date_end: 2019-03-24 03:59:59.999999+00:00


      dates2:
      local_date_start: 2015-02-12 00:00:00-03:00
      local_date_end: 2019-03-23 23:59:59.999999-03:00
      utc_date_start: 2015-02-12 03:00:00+00:00
      utc_date_end: 2019-03-24 02:59:59.999999+00:00


      Note the inconsistent UTC offset (that particular timezone switched to DST on Mar 23rd). But when I try to replicate the issue using the following code:



      import pytz 
      import datetime
      from django.utils import timezone

      now1 = timezone.now() - datetime.timedelta(days=2)
      now2 = pytz.utc.localize(datetime.datetime.now()) - datetime.timedelta(days=2)

      seller_timezone = pytz.timezone('America/Asuncion')

      print(now1.astimezone(seller_timezone).replace(
      hour=23, minute=59, second=59, microsecond=999999
      ))
      print(now2.astimezone(seller_timezone).replace(
      hour=23, minute=59, second=59, microsecond=999999
      ))


      The output is correct:



      2019-03-23 23:59:59.999999-03:00
      2019-03-23 23:59:59.999999-03:00


      I'm hoping someone can understand why this behavior is happening and how I might avoid the inconsistencies if so.










      share|improve this question
















      I'm experiencing strange behavior when attempting to convert between UTC and specific timezones. I'd love for someone to explain why I'm seeing this behavior and what the more "correct" way of getting timezone information might be.



      Code:



      import pytz
      import datetime
      from django.utils import timezone

      print(timezone.now())
      print(pytz.utc.localize(datetime.datetime.now()))
      print('n')

      def get_local_and_utc_date_ranges(days=1500, days_ago=2, local_timezone="America/Asuncion"):
      seller_timezone = pytz.timezone(local_timezone)
      utc_timezone = pytz.utc

      seller_today = timezone.now().astimezone(seller_timezone)
      seller_days_ago = seller_today - timezone.timedelta(days=days_ago)

      local_date_end = seller_days_ago.replace(hour=23, minute=59, second=59, microsecond=999999)
      local_date_start = (local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)

      utc_date_end = local_date_end.astimezone(utc_timezone)
      utc_date_start = local_date_start.astimezone(utc_timezone)

      date_ranges =
      "local_date_end": local_date_end,
      "local_date_start": local_date_start,
      "utc_date_end": utc_date_end,
      "utc_date_start": utc_date_start,


      return date_ranges


      def get_utc_and_local_date_ranges(days=1500, days_ago=2, local_timezone='America/Asuncion'):
      seller_timezone = pytz.timezone(local_timezone)
      utc_timezone = pytz.utc

      utc_today = datetime.datetime.utcnow()
      utc_days_ago = utc_today - datetime.timedelta(days=days_ago)

      local_date_end = seller_timezone.localize(utc_days_ago).replace(
      hour=23, minute=59, second=59, microsecond=999999
      )
      local_date_start = (local_date_end - datetime.timedelta(days=days)).replace(
      hour=0, minute=0, second=0, microsecond=0
      )
      utc_date_end = local_date_end.astimezone(utc_timezone)
      utc_date_start = local_date_start.astimezone(utc_timezone)

      date_ranges =
      'local_date_end': local_date_end,
      'local_date_start': local_date_start,
      'utc_date_end': utc_date_end,
      'utc_date_start': utc_date_start,


      return date_ranges



      days = 1500
      days_ago = 2

      dates = get_local_and_utc_date_ranges(days=days, days_ago=days_ago)
      dates2 = get_utc_and_local_date_ranges(days=days, days_ago=days_ago)


      print('dates1:')
      print('local_date_start:', dates['local_date_start'])
      print('local_date_end:', dates['local_date_end'])
      print('utc_date_start:', dates['utc_date_start'])
      print('utc_date_end:', dates['utc_date_end'])
      print('n')

      print('dates2:')
      print('local_date_start:', dates2['local_date_start'])
      print('local_date_end:', dates2['local_date_end'])
      print('utc_date_start:', dates2['utc_date_start'])
      print('utc_date_end:', dates2['utc_date_end'])
      print('n')


      Output:



      2019-03-25 18:57:55.929908+00:00
      2019-03-25 18:57:55.930005+00:00


      dates1:
      local_date_start: 2015-02-12 00:00:00-04:00
      local_date_end: 2019-03-23 23:59:59.999999-04:00
      utc_date_start: 2015-02-12 04:00:00+00:00
      utc_date_end: 2019-03-24 03:59:59.999999+00:00


      dates2:
      local_date_start: 2015-02-12 00:00:00-03:00
      local_date_end: 2019-03-23 23:59:59.999999-03:00
      utc_date_start: 2015-02-12 03:00:00+00:00
      utc_date_end: 2019-03-24 02:59:59.999999+00:00


      Note the inconsistent UTC offset (that particular timezone switched to DST on Mar 23rd). But when I try to replicate the issue using the following code:



      import pytz 
      import datetime
      from django.utils import timezone

      now1 = timezone.now() - datetime.timedelta(days=2)
      now2 = pytz.utc.localize(datetime.datetime.now()) - datetime.timedelta(days=2)

      seller_timezone = pytz.timezone('America/Asuncion')

      print(now1.astimezone(seller_timezone).replace(
      hour=23, minute=59, second=59, microsecond=999999
      ))
      print(now2.astimezone(seller_timezone).replace(
      hour=23, minute=59, second=59, microsecond=999999
      ))


      The output is correct:



      2019-03-23 23:59:59.999999-03:00
      2019-03-23 23:59:59.999999-03:00


      I'm hoping someone can understand why this behavior is happening and how I might avoid the inconsistencies if so.







      django python-3.x datetime timezone timezone-offset






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 29 at 20:56







      Blairg23

















      asked Mar 25 at 19:04









      Blairg23Blairg23

      5,1951 gold badge44 silver badges51 bronze badges




      5,1951 gold badge44 silver badges51 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          2














          Your get_local_and_utc_date_ranges() function is producing incorrect results because it's doing datetime arithmetic (i.e. subtracting a timedelta) with a localized time, which doesn't work.



          seller_today = timezone.now().astimezone(seller_timezone)
          seller_days_ago = seller_today - timezone.timedelta(days=days_ago)


          This is noted in the datetime module documentation:




          As for addition, the result [of subtracting a timedelta] has the same tzinfo attribute as the input datetime, and no time zone adjustments are done even if the input is aware.




          This is also noted in the pytz documentation:




          If you perform date arithmetic on local times that cross DST boundaries, the result may be in an incorrect timezone.




          pytz offers a fix:




          A normalize() method is provided to correct this.




          So you could use:



          seller_days_ago = seller_timezone.normalize(seller_today - timezone.timedelta(days=days_ago))
          ...
          local_date_start = seller_timezone.normalize(local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)


          However, the documentation also notes that:




          The preferred way of dealing with times is to always work in UTC.




          So a better solution would be to only do arithmetic in UTC:



          utc_today = datetime.datetime.utcnow()
          utc_date_end = utc_today - datetime.timedelta(days=days_ago)
          utc_date_start = utc_date_end - datetime.timedelta(days=days)

          local_date_end = seller_timezone.localize(utc_date_end).replace(hour=23, minute=59, second=59, microsecond=999999)
          local_date_start = seller_timezone.localize(utc_date_start).replace(hour=0, minute=0, second=0, microsecond=0)





          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55344832%2fexperiencing-odd-output-from-django-utils-timezone-now-datetime-datetime-now%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            Your get_local_and_utc_date_ranges() function is producing incorrect results because it's doing datetime arithmetic (i.e. subtracting a timedelta) with a localized time, which doesn't work.



            seller_today = timezone.now().astimezone(seller_timezone)
            seller_days_ago = seller_today - timezone.timedelta(days=days_ago)


            This is noted in the datetime module documentation:




            As for addition, the result [of subtracting a timedelta] has the same tzinfo attribute as the input datetime, and no time zone adjustments are done even if the input is aware.




            This is also noted in the pytz documentation:




            If you perform date arithmetic on local times that cross DST boundaries, the result may be in an incorrect timezone.




            pytz offers a fix:




            A normalize() method is provided to correct this.




            So you could use:



            seller_days_ago = seller_timezone.normalize(seller_today - timezone.timedelta(days=days_ago))
            ...
            local_date_start = seller_timezone.normalize(local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)


            However, the documentation also notes that:




            The preferred way of dealing with times is to always work in UTC.




            So a better solution would be to only do arithmetic in UTC:



            utc_today = datetime.datetime.utcnow()
            utc_date_end = utc_today - datetime.timedelta(days=days_ago)
            utc_date_start = utc_date_end - datetime.timedelta(days=days)

            local_date_end = seller_timezone.localize(utc_date_end).replace(hour=23, minute=59, second=59, microsecond=999999)
            local_date_start = seller_timezone.localize(utc_date_start).replace(hour=0, minute=0, second=0, microsecond=0)





            share|improve this answer





























              2














              Your get_local_and_utc_date_ranges() function is producing incorrect results because it's doing datetime arithmetic (i.e. subtracting a timedelta) with a localized time, which doesn't work.



              seller_today = timezone.now().astimezone(seller_timezone)
              seller_days_ago = seller_today - timezone.timedelta(days=days_ago)


              This is noted in the datetime module documentation:




              As for addition, the result [of subtracting a timedelta] has the same tzinfo attribute as the input datetime, and no time zone adjustments are done even if the input is aware.




              This is also noted in the pytz documentation:




              If you perform date arithmetic on local times that cross DST boundaries, the result may be in an incorrect timezone.




              pytz offers a fix:




              A normalize() method is provided to correct this.




              So you could use:



              seller_days_ago = seller_timezone.normalize(seller_today - timezone.timedelta(days=days_ago))
              ...
              local_date_start = seller_timezone.normalize(local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)


              However, the documentation also notes that:




              The preferred way of dealing with times is to always work in UTC.




              So a better solution would be to only do arithmetic in UTC:



              utc_today = datetime.datetime.utcnow()
              utc_date_end = utc_today - datetime.timedelta(days=days_ago)
              utc_date_start = utc_date_end - datetime.timedelta(days=days)

              local_date_end = seller_timezone.localize(utc_date_end).replace(hour=23, minute=59, second=59, microsecond=999999)
              local_date_start = seller_timezone.localize(utc_date_start).replace(hour=0, minute=0, second=0, microsecond=0)





              share|improve this answer



























                2












                2








                2







                Your get_local_and_utc_date_ranges() function is producing incorrect results because it's doing datetime arithmetic (i.e. subtracting a timedelta) with a localized time, which doesn't work.



                seller_today = timezone.now().astimezone(seller_timezone)
                seller_days_ago = seller_today - timezone.timedelta(days=days_ago)


                This is noted in the datetime module documentation:




                As for addition, the result [of subtracting a timedelta] has the same tzinfo attribute as the input datetime, and no time zone adjustments are done even if the input is aware.




                This is also noted in the pytz documentation:




                If you perform date arithmetic on local times that cross DST boundaries, the result may be in an incorrect timezone.




                pytz offers a fix:




                A normalize() method is provided to correct this.




                So you could use:



                seller_days_ago = seller_timezone.normalize(seller_today - timezone.timedelta(days=days_ago))
                ...
                local_date_start = seller_timezone.normalize(local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)


                However, the documentation also notes that:




                The preferred way of dealing with times is to always work in UTC.




                So a better solution would be to only do arithmetic in UTC:



                utc_today = datetime.datetime.utcnow()
                utc_date_end = utc_today - datetime.timedelta(days=days_ago)
                utc_date_start = utc_date_end - datetime.timedelta(days=days)

                local_date_end = seller_timezone.localize(utc_date_end).replace(hour=23, minute=59, second=59, microsecond=999999)
                local_date_start = seller_timezone.localize(utc_date_start).replace(hour=0, minute=0, second=0, microsecond=0)





                share|improve this answer















                Your get_local_and_utc_date_ranges() function is producing incorrect results because it's doing datetime arithmetic (i.e. subtracting a timedelta) with a localized time, which doesn't work.



                seller_today = timezone.now().astimezone(seller_timezone)
                seller_days_ago = seller_today - timezone.timedelta(days=days_ago)


                This is noted in the datetime module documentation:




                As for addition, the result [of subtracting a timedelta] has the same tzinfo attribute as the input datetime, and no time zone adjustments are done even if the input is aware.




                This is also noted in the pytz documentation:




                If you perform date arithmetic on local times that cross DST boundaries, the result may be in an incorrect timezone.




                pytz offers a fix:




                A normalize() method is provided to correct this.




                So you could use:



                seller_days_ago = seller_timezone.normalize(seller_today - timezone.timedelta(days=days_ago))
                ...
                local_date_start = seller_timezone.normalize(local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)


                However, the documentation also notes that:




                The preferred way of dealing with times is to always work in UTC.




                So a better solution would be to only do arithmetic in UTC:



                utc_today = datetime.datetime.utcnow()
                utc_date_end = utc_today - datetime.timedelta(days=days_ago)
                utc_date_start = utc_date_end - datetime.timedelta(days=days)

                local_date_end = seller_timezone.localize(utc_date_end).replace(hour=23, minute=59, second=59, microsecond=999999)
                local_date_start = seller_timezone.localize(utc_date_start).replace(hour=0, minute=0, second=0, microsecond=0)






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 26 at 21:19

























                answered Mar 25 at 20:33









                Kevin Christopher HenryKevin Christopher Henry

                25.5k5 gold badges70 silver badges64 bronze badges




                25.5k5 gold badges70 silver badges64 bronze badges


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55344832%2fexperiencing-odd-output-from-django-utils-timezone-now-datetime-datetime-now%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현