Convert UTC timezone to IST python - python-3.x

The following code line gives me the UTC timing on the production server.
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
Please suggest a way to convert above UTC timezone to IST(Indian Standard Time) timing.

datetime.now() gives you a naive datetime object that represents local time according to the setting of the machine you run the script on (which in this case just happens to be UTC since it's a server). See the docs.
To get "now" in a specific timezone, you can set the tz property appropriately.
Python >= 3.9: you have zoneinfo in the standard lib to do this:
from zoneinfo import ZoneInfo
dtobj = datetime.now(tz=ZoneInfo('Asia/Kolkata'))
print(dtobj)
>>> 2020-07-23 11:11:43.594442+05:30
Python < 3.9: I'd recommend the dateutil package to do so (or use zoneinfo via backports.zoneinfo).
from datetime import datetime
from dateutil.tz import gettz
dtobj = datetime.now(tz=gettz('Asia/Kolkata'))
print(dtobj)
>>> 2020-07-23 11:08:54.032651+05:30

from datetime import datetime
import pytz
tz_NY = pytz.timezone('Asia/Kolkata')
datetime_NY = datetime.now(tz_NY)
print("India time:", datetime_NY.strftime("%Y-%m-%d %H:%M:%S.%f"))
>>India time: 2021-05-03 12:25:21.877976

Related

Python code works in IDE but when compiled in a .exe it doesn't work

I have written a basic program that takes the current internet time and adjusts the system time to be 2 mins ahead. The code can be seen below:
from datetime import timedelta
from datetime import datetime
import win32api
from urllib.request import urlopen
import admin
res = urlopen('http://just-the-time.appspot.com/')
result = res.read().strip()
now = result.decode('utf-8')
new_time = datetime.strptime(now, "%Y-%m-%d %H:%M:%S") + timedelta(hours=0, minutes=2, seconds=0)
year = new_time.year
month = new_time.month
day = new_time.day
hour = new_time.hour
minute = new_time.minute
second = new_time.second
win32api.SetSystemTime(year, month, 0, day, hour, minute, second,0)
print(new_time)
The program works perfectly when using the Pycharm IDE, however when I try to compile the code into an .exe using auto-py-to-exe or pyinstaller, the code runs but no changes are made to the system time. I have tried running as administrator but this doesn't seem to help. Can anyone help?

Is there a way to find the local timezone with datetime?

I am trying to make some code that creates a clock using the user's local time with the datetime library.
import datetime as dt
import os
import time
z = dt.datetime.now()
def local_time():
def time_check(t):
if t < 10:
t = "0{}".format(t)
else:
t = t
return t
p = dt.datetime.now()
hour = p.hour
minute = p.minute
second = p.second
hour = time_check(hour)
minute = time_check(minute)
second = time_check(second)
local_time = '{}:{}:{}'.format(hour, minute, second)
return local_time
time_zone = z.timezone()
for i in range(999999999999999999999):
print("Time: {} {}".format(local_time(), time_zone))
time.sleep(1)
os.system("cls")
What I am doing is gathering the hour, minute, and second of the local time, and constantly updating it in the terminal, and deleting the previous time.
This works fine, but I am also trying to display the timezone of the user, and I am having a hard time trying to find a way to do it. Does anyone know a way? Thanks.
Importing the python-dateutil library should make this easier. Install the library with the pip install python-dateutil command at the terminal if you don't have it installed beforehand. Once you do that, test the below code:
from datetime import *
from dateutil.tz import *
print(datetime.now(tzlocal()).tzname())
print(datetime(2021, 6, 2, 16, 00, tzinfo=tzlocal()).tzname())
#Output
#SA Western Standard Time
#SA Western Standard Time
Using tzlocal() and tzname() together will give you the current timezone. The dateutil library is very powerful and useful. Check out the full documentation HERE.
Hopefully that helped.

Python datetime parsing timestamp with timezone

I ran into this problem a while back ago where parsing an ISO string with time zone data and parsing a timestamp (supposedly of the same time) will give different results. I have written a test to check this behavior and it seems pretty inconsistent:
from pytz import timezone as tz
from datetime import datetime
timezone = "Australia/Sydney"
start_time = "2021-05-04T08:12:00"
tz_object = tz(timezone)
naive_datetime = datetime.fromisoformat(start_time)
zoned_time = datetime(naive_datetime.year, naive_datetime.month, naive_datetime.day, naive_datetime.hour, naive_datetime.minute, naive_datetime.second, tzinfo=tz_object)
parsed_time = datetime.fromtimestamp(zoned_time.timestamp(), tz_object)
assert zoned_time.time() == naive_datetime.time()
assert zoned_time.time() == parsed_time.time()
This test produces the following output
File "test.py", line 13, in <module>
assert zoned_time.time() == parsed_time.time()
AssertionError
Unless I'm missing something I can only conclude that the time resulting from this line
parsed_time = datetime.fromtimestamp(zoned_time.timestamp(), tz_object)
Is producing a different time than parsing the actual ISO string. Typically I'd expect the timestamp from the parsed time return a timestamp referring to 8:12 am in the time zone it was assigned.
Is this behavior expected?
Did I miss something?
With Python 3.9, use zoneinfo. Note that there is a deprecation shim for pytz if required.
Your code then works fine like
from datetime import datetime
from zoneinfo import ZoneInfo
timezone = "Australia/Sydney"
tz_object = ZoneInfo(timezone)
start_time = "2021-05-04T08:12:00"
naive_datetime = datetime.fromisoformat(start_time)
zoned_time = datetime(naive_datetime.year, naive_datetime.month, naive_datetime.day, naive_datetime.hour, naive_datetime.minute, naive_datetime.second, tzinfo=tz_object)
parsed_time = datetime.fromtimestamp(zoned_time.timestamp(), tz_object)
assert zoned_time.time() == naive_datetime.time()
assert zoned_time.time() == parsed_time.time()
As to why you got an assertion error: with pytz you need to localize the datetime object with the time zone; never set a tzinfo directly with pytz.

Inconsistent datetime object in Python3 and Django2

Python 3, Django 2
I am trying to get a function to consistently return a datetime object.
Here are the conditions where it does and does not work.
I have a function that generates a datetime object with an offset like so:
from django.conf import settings
from datetime import datetime
def off_time():
date = datetime.now()
offset = settings.TIME_OFFSET
offtime = date + offset
return offtime
TIME_OFFSET is generated in settings thus:
from datetime import timedelta
TIME_OFFSET = timedelta(days=370000)
If I save to a model object like this:
from django.db import models
import stellar.physics_tools
class Test(models.Model):
cdate = models.DateTimeField(default=stellar.physics_tools.off_time, help_text='When Generated')
and then work on the cdate, I can do this:
cdate = test.cdate
creation_date = cdate.strftime("%d-%m-%Y %H:%M:%S")
and it works ok.
but if I try this:
newtime = stellar.physics_tools.off_time
return newtime.strftime("%d-%m-%Y %H:%M:%S")
I get:
'function' object has no attribute 'strftime'
I need this function to return an object that I can use .strftime on, at least.
Any help appreciated. Thanks.
For this to work I need to call the function with () like this:
newtime = stellar.physics_tools.off_time()
I was not doing this because if I did this in the Django model construction it returns the value created when the class is defined, which is not what I want.
In short I still need to use stellar.physics_tools.off_time in the Django model, but when calling the function outside of this I need to use stellar.physics_tools.off_time().

Python AWS function error :module initialization error name 'tz' is not defined

I am Trying to run a python code using AWS function,I have added .zip folder with all dependency and proper structure but gettiing below error .
But when executing same code with Node js working fine .
import pytz
import urllib3
import calendar
def lambda_handler(event, context):
tz=pytz.timezone('Asia/Calcutta')
utc = datetime.utcnow()
utc = pytz.utc.localize(utc, is_dst=None).astimezone(tz)
time = utc.strftime("%H") # gmt/utc time
text = ""
textaum = ""
Function Logs:
START RequestId: c5f433f7-2a61-11e8-9d30-b9dad0fd99997 Version: $LATEST
module initialization error: name 'tz' is not defined
It is all with the scope of the variable, you have the variable tz in function definition, outside that it is not accessible ...
Plus you have a lot of errors in your code say for example datetime is not defined so you need to import the datetime module, please correct them as well

Resources