Home > front end >  Python datetime.today() Showing different time in different python programms
Python datetime.today() Showing different time in different python programms

Time:01-15

I am having 2 different python file, views.py in django and a test.py .I use test.py to write a specific function and check if iam getting desired output,and if yes, i will copy that code to views.py in my django project. Today i was writting a function to calculate time intervals of 15 mins and populate a list. When i was trying to do print('Today: ',datetime.today()) in test.py it was giving the correct output and a different output in views.py

Here's the output in both

test.py: Today: 2022-01-13 20:28:45.613094

views.py: Today: 2022-01-13 14:58:25.850835

Note:In my views.py there are other function which uses datetime libraries but iam sure that they are not interfering with each other

Here's the Code i use to generate a list of time with interval of 15 mins:

def datetime_range(start, end, delta):
  current = start
  while current <= end:
    yield current
    current  = delta

def create():
  print('Today: ',datetime.today())  #This is where the problem occurs!
  a=datetime.strftime(datetime.now(),'%I:%M')
  h=a[0:2]


  dts = [dt.strftime('%I:%M') for dt in 
     datetime_range(datetime(2022, 1, 1,int(h)), datetime(2022, 1, 1,9), 
     timedelta(minutes=15))]

 new=[]
 for d in dts:
    if datetime.strptime(d,'%I:%M') > datetime.strptime(a,'%I:%M'):
          new.append(d)


 return new

CodePudding user response:

Your offset of 5 and a half hours between the two results indicates you are probably located in India, and you found an issue with timezones. Try using datetime.utcnow() instead, and continue from there.

https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow

CodePudding user response:

if you want, you can see this post about timezone on settings

https://quick-adviser.com/how-do-i-change-timezone-in-django-unchained/

  •  Tags:  
  • Related