How to get current time in india in python - python

How would I get the current timestamp in python of India?
I tried time.ctime() and datetime.utcnow() also datetime.now()
but they all return a different time than here it is in india.
The codes above return the time that not match the current time on my computer. and the time in my computer is definitely correct.

from pytz import timezone
from datetime import datetime
ind_time = datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S.%f')
print(ind_time)
>>> "2020-08-28 11:56:37.010822"

You can use timedelta object in datetime module:
since the Indian Standard Time (IST) is 5.5 hours ahead of Coordinated Universal Time (UTC), we can shift the UTC time to 5hrs and 30 mins.
import datetime as dt
dt_India_naive = dt.datetime.utcnow() + dt.timedelta(hours=5, minutes=30)
dt_India_aware = dt.datetime.now(dt.timezone(dt.timedelta(hours=5, minutes=30)))
dt_UTC_naive = dt.datetime.utcnow()
dt_UTC_aware = dt.datetime.now(dt.timezone.utc)
max_len = len(max(['UTC Time', 'Indian Time'], key=len))
print(f"{'UTC Time' :<{max_len}} - {dt_UTC_aware:%d-%b-%y %H:%M:%S}")
print(f"{'Indian Time':<{max_len}} - {dt_India_aware:%d-%b-%y %H:%M:%S}")
# Both offset-naive and offset-aware will provide same results in this sitatuiion
Result:-
UTC Time - 20-Feb-23 03:29:12
Indian Time - 20-Feb-23 08:59:12

You can do it with pytz:
import datetime,pytz
dtobj1=datetime.datetime.utcnow() #utcnow class method
print(dtobj1)
dtobj3=dtobj1.replace(tzinfo=pytz.UTC) #replace method
#print(pytz.all_timezones) => To see all timezones
dtobj_india=dtobj3.astimezone(pytz.timezone("Asia/Calcutta")) #astimezone method
print(dtobj_india)
result:
2020-08-28 06:01:13.833290
2020-08-28 11:31:13.833290+05:30

Related

Converting UTC Time formatted string into Local Time Zone in Python [duplicate]

Is there an elegant way to display the current time in another time zone?
I would like to have something with the general spirit of:
cur = <Get the current time, perhaps datetime.datetime.now()>
print("Local time {}".format(cur))
print("Pacific time {}".format(<something like cur.tz('PST')>))
print("Israeli time {}".format(<something like cur.tz('IST')>))
A simpler method:
from datetime import datetime
from pytz import timezone
south_africa = timezone('Africa/Johannesburg')
sa_time = datetime.now(south_africa)
print sa_time.strftime('%Y-%m-%d_%H-%M-%S')
You could use the pytz library:
>>> from datetime import datetime
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = pytz.timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = pytz.timezone('Europe/Amsterdam')
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print loc_dt.strftime(fmt)
2002-10-27 06:00:00 EST-0500
>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'
Python 3.9 (or higher): use zoneinfo from the standard lib:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
# Israel and US/Pacific time:
now_Israel = datetime.now(ZoneInfo('Israel'))
now_Pacific = datetime.now(ZoneInfo('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00
# for reference, local time and UTC:
now_local = datetime.now().astimezone()
now_UTC = datetime.now(tz=timezone.utc)
print(f"Local time {now_local.isoformat(timespec='seconds')}")
print(f"UTC {now_UTC.isoformat(timespec='seconds')}")
# Local time 2021-03-26T16:09:18+01:00 # I'm on Europe/Berlin
# UTC 2021-03-26T15:09:18+00:00
Note: there's a deprecation shim for pytz.
older versions of Python 3: you can either use zoneinfo via the backports module or use dateutil instead. dateutil's tz.gettz follows the same semantics as zoneinfo.ZoneInfo:
from dateutil.tz import gettz
now_Israel = datetime.now(gettz('Israel'))
now_Pacific = datetime.now(gettz('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00
One way, through the timezone setting of the C library, is
>>> cur=time.time()
>>> os.environ["TZ"]="US/Pacific"
>>> time.tzset()
>>> time.strftime("%T %Z", time.localtime(cur))
'03:09:51 PDT'
>>> os.environ["TZ"]="GMT"
>>> time.strftime("%T %Z", time.localtime(cur))
'10:09:51 GMT'
The shortest ans of the question can be like:
from datetime import datetime
import pytz
print(datetime.now(pytz.timezone('Asia/Kolkata')))
This will print:
2019-06-20 12:48:56.862291+05:30
This script which makes use of the pytz and datetime modules is structured as requested:
#!/usr/bin/env python3
import pytz
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc)
PST = pytz.timezone("US/Pacific")
IST = pytz.timezone("Asia/Jerusalem")
print("UTC time {}".format(utc_dt.isoformat()))
print("Local time {}".format(utc_dt.astimezone().isoformat()))
print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Israeli time {}".format(utc_dt.astimezone(IST).isoformat()))
It outputs the following:
$ ./timezones.py
UTC time 2019-02-23T01:09:51.452247+00:00
Local time 2019-02-23T14:09:51.452247+13:00
Pacific time 2019-02-22T17:09:51.452247-08:00
Israeli time 2019-02-23T03:09:51.452247+02:00
This is my implementation:
from datetime import datetime
from pytz import timezone
def local_time(zone='Asia/Jerusalem'):
other_zone = timezone(zone)
other_zone_time = datetime.now(other_zone)
return other_zone_time.strftime('%T')
Can specify timezone by importing the modules datetime from datetime and pytx.
from datetime import datetime
import pytz
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))
tz_India = pytz.timezone('Asia/Kolkata')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))
If you want a method which doesn't require importing pytz or any specific timezone libraries, you can do it in this way which only imports datetime. By using datetime to get the current UTC time then adding the timezone modifier, any desired timezone can be achieved.
For example, the timezone in New York is 4 hours behind UTC time, or UTC-04:00.
This means we can use this code to find the current time in New York:
import datetime
utc_time = datetime.datetime.utc(now)
tz_modifier = datetime.datetime.timedelta(hours=-4)
tz_time = utc_time + tz_modifier
print(tz_time)
To make this more "elegant" as was wanted, this method could be used:
from datetime import datetime, timedelta
utc = datetime.utcnow()
print("China time {}".format(utc+timedelta(hours=8)))
print("Greece time {}".format(utc+timedelta(hours=3)))
print("Hawaii time {}".format(utc+timedelta(hours=-10)))
The downside to this method is that the actual UTC differences of the timezones must be known already.
I need time info all time time, so I have this neat .py script on my server that lets me just select and deselect what time zones I want to display in order of east->west.
It prints like this:
Australia/Sydney : 2016-02-09 03:52:29 AEDT+1100
Asia/Singapore : 2016-02-09 00:52:29 SGT+0800
Asia/Hong_Kong : 2016-02-09 00:52:29 HKT+0800
EET : 2016-02-08 18:52:29 EET+0200
CET : 2016-02-08 17:52:29 CET+0100 <- you are HERE
UTC : 2016-02-08 16:52:29 UTC+0000
Europe/London : 2016-02-08 16:52:29 GMT+0000
America/New_York : 2016-02-08 11:52:29 EST-0500
America/Los_Angeles : 2016-02-08 08:52:29 PST-0800
Here source code is one .py file on my github here:
https://github.com/SpiRaiL/timezone
Or the direct file link:
https://raw.githubusercontent.com/SpiRaiL/timezone/master/timezone.py
In the file is a list like this:
Just put a 'p' in the places you want printed.
Put a 'h' for your own time zone if you want it specially marked.
(' ','America/Adak'), (' ','Africa/Abidjan'), (' ','Atlantic/Azores'), (' ','GB'),
(' ','America/Anchorage'), (' ','Africa/Accra'), (' ','Atlantic/Bermuda'), (' ','GB-Eire'),
(' ','America/Anguilla'), (' ','Africa/Addis_Ababa'), (' ','Atlantic/Canary'), (' ','GMT'),
(' ','America/Antigua'), (' ','Africa/Algiers'), (' ','Atlantic/Cape_Verde'), (' ','GMT+0'),
(' ','America/Araguaina'), (' ','Africa/Asmara'), (' ','Atlantic/Faeroe'), (' ','GMT-0'),
(' ','America/Argentina/Buenos_Aires'), (' ','Africa/Asmera'), (' ','Atlantic/Faroe'), (' ','GMT0'),
(' ','America/Argentina/Catamarca'), (' ','Africa/Bamako'), (' ','Atlantic/Jan_Mayen'), (' ','Greenwich'),
(' ','America/Argentina/ComodRivadavia'), (' ','Africa/Bangui'), (' ','Atlantic/Madeira'), (' ','HST'),
(' ','America/Argentina/Cordoba'), (' ','Africa/Banjul'), (' ','Atlantic/Reykjavik'), (' ','Hongkong'),
I end up using pandas a lot in my code, and don't like importing extra libraries if I don't have to, so here's a solution I'm using that's simple and clean:
import pandas as pd
t = pd.Timestamp.now('UTC') #pull UTC time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_UTC_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format
t = pd.Timestamp.now(tz='US/Eastern') #pull Eastern (EDT or EST, as current) time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_EAST_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format
print(f"The current UTC time is: {now_UTC_rounded} (rounded to the nearest 10 min)")
print(f"The current US/Eastern time is: {now_EAST_rounded} (rounded to the nearest 10 min)")
Outputs:
The current UTC time is: 1800 (rounded to the nearest 10 min)
The current US/Eastern time is: 1400 (rounded to the nearest 10 min)
(actual Eastern time was 14:03)
The rounding feature is nice because if you're trying to trigger something at a specific time, like on the hour, you can miss by 4 minutes on either side and still get a match.
Just showing off features - obviously you don't need to use the round if you don't want!
You can check this question.
Or try using pytz. Here you can find an installation guide with some usage examples.

Python astimezone 1 hour behind expected result compared to adding timedelta to UTC date

I am trying to do some testing with time offsets from UTC. I have tried two methods as shown in the code listing below:
Adding timedelta to UTC datetime
Using astimezone method on UTC datetime
In the short test program below the resultant date from astimezone method is 1 hour behind. I do not understand why??
from datetime import datetime, timedelta, timezone
if __name__ == "__main__":
utc_now = datetime.utcnow()
target_time = int((utc_now + timedelta(hours=10)).timestamp())
timestamp = utc_now.astimezone(timezone(timedelta(hours=10)))
print(f"datetime.utcnow() = {utc_now.isoformat()}")
print(
f"datetime.utcnow() + 10 hours using timedelta = {datetime.fromtimestamp(target_time).isoformat()}"
)
print(f"datetime.utcnow() + 10 hours using astimezone = {timestamp.isoformat()}")
datetime.utcnow() = 2021-09-04T16:12:53.753059
datetime.utcnow() + 10 hours using timedelta = 2021-09-05T02:12:53
datetime.utcnow() + 10 hours using astimezone = 2021-09-05T01:12:53.753059+10:00
Edit - Update - datetime.now (timezone.utc )
from datetime import datetime, timedelta, timezone
if __name__ == "__main__":
utc_now = datetime.now(timezone.utc)
target_time = int((utc_now + timedelta(hours=10)).timestamp())
timestamp = utc_now.astimezone(timezone(timedelta(hours=10)))
print(f"datetime.utcnow() = {utc_now.isoformat()}")
print(
"datetime.utcnow() + 10 hours using timedelta ="
f" {datetime.fromtimestamp(target_time).isoformat()}"
)
print(f"datetime.utcnow() + 10 hours using astimezone = {timestamp.isoformat()}")
Tried to make timezone aware UTC datetime now with the same result.
How do I use astimezone to get an equivalent result?
The problem here is the assumption that datetime.utcnow() gives you UTC. It does not. It gives you a naive datetime object that Python still treats as local time although hours, minutes etc. resemble UTC.
Set tzinfo adequately to get consistent results (don't use utcnow at all if possible! - unless you know what you're doing):
from datetime import datetime, timedelta, timezone
utc_now = datetime(2021, 9, 4, tzinfo=timezone.utc)
target_time = int((utc_now + timedelta(hours=10)).timestamp())
timestamp = utc_now.astimezone(timezone(timedelta(hours=10)))
print(f"utc_now = {utc_now.isoformat()}")
print(f"utc_now + 10 hours using timedelta = {datetime.fromtimestamp(target_time, tz=timezone.utc).isoformat()}")
print(f"utc_now + 10 hours using astimezone = {timestamp.isoformat()}")
# utc_now = 2021-09-04T00:00:00+00:00
# utc_now + 10 hours using timedelta = 2021-09-04T10:00:00+00:00
# utc_now + 10 hours using astimezone = 2021-09-04T10:00:00+10:00
The key here is understanding the difference between naive datetime (=local time by default) and aware datetime (the time zone you set...). For more time zone handling, see also the zoneinfo lib.
an aspect that is also relevant here in the context of working with time zones in Python: timedelta arithmetic is wall time arithmetic - i.e. what you would observe on a wall clock that gets adjusted to DST active/inactive. In the following example, I add 24 hours:
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
t0 = datetime(2021, 10, 30, 20, tzinfo=ZoneInfo("Europe/Berlin")) # DST active
t1 = t0 + timedelta(hours=24) # add 24 hours -> DST is inactive
print(t0, t1)
# 2021-10-30 20:00:00+02:00 2021-10-31 20:00:00+01:00
print((t1-t0).total_seconds()/3600)
# 24.0
Now watch how they become 25 hours - not because of magic but because of the wall clock would show local time, not UTC...
t0_utc, t1_utc = t0.astimezone(ZoneInfo("UTC")), t1.astimezone(ZoneInfo("UTC"))
print(t0_utc, t1_utc)
# 2021-10-30 18:00:00+00:00 2021-10-31 19:00:00+00:00
print((t1_utc-t0_utc).total_seconds()/3600)
# 25.0
Note: since Europe/Berlin is the time zone my OS is configured to use, this would also work with t0 and t1 being naive datetime objects!

Convert local time to UNIX

I'm new to python and I'm trying to get the actual minutes passed every day since 7:00.
I am using mktime to get now_date1 and now_date2 in seconds, and then the plan it's to subtract and divide by 60 to get the minutes.
But I get the following error:
AttributeError: 'str' object has no attribute 'timetuple'
It's this the correct approach?
Here it's the code
import time
import pytz
from datetime import datetime
from time import mktime as mktime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
now_date1 = now_date.strftime('%H:%M:%S')
now_date2 = now_date.strftime('7:00:00')
# Convert to Unix timestamp
d1_ts = time.mktime(now_date1.timetuple())
strftime returns a string. Not what you want.
You were pretty close, but there's no need to put time in the mix. Just modify your code like this and use time delta from datetime (inspired by How to calculate the time interval between two time strings):
import pytz
from datetime import datetime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
from datetime import datetime
FMT = '%H:%M:%S'
now_date1 = now_date.strftime(FMT)
now_date2 = now_date.strftime('7:00:00')
tdelta = datetime.strptime(now_date1, FMT) - datetime.strptime(now_date2, FMT)
print(tdelta)
I get: 6:40:42 which seems to match since it's 12:42 here.
To get the result in minutes just do:
tdelta.seconds//60
(note that the dates have only correct hour/time/seconds, the year, month, etc.. are 1900 ... since they're not used)
I think something like this might work:
import time
import datetime
from time import mktime as mktime
#current time
now_date = datetime.datetime.now()
#time at 7am
today = datetime.date.today()
now_date2 = datetime.datetime(today.year, today.month, today.day, 7, 0, 0, 0)
#difference in minutes
(now_date - now_date2).days * 24 * 60

Display the time in a different time zone

Is there an elegant way to display the current time in another time zone?
I would like to have something with the general spirit of:
cur = <Get the current time, perhaps datetime.datetime.now()>
print("Local time {}".format(cur))
print("Pacific time {}".format(<something like cur.tz('PST')>))
print("Israeli time {}".format(<something like cur.tz('IST')>))
A simpler method:
from datetime import datetime
from pytz import timezone
south_africa = timezone('Africa/Johannesburg')
sa_time = datetime.now(south_africa)
print sa_time.strftime('%Y-%m-%d_%H-%M-%S')
You could use the pytz library:
>>> from datetime import datetime
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = pytz.timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = pytz.timezone('Europe/Amsterdam')
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print loc_dt.strftime(fmt)
2002-10-27 06:00:00 EST-0500
>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'
Python 3.9 (or higher): use zoneinfo from the standard lib:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
# Israel and US/Pacific time:
now_Israel = datetime.now(ZoneInfo('Israel'))
now_Pacific = datetime.now(ZoneInfo('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00
# for reference, local time and UTC:
now_local = datetime.now().astimezone()
now_UTC = datetime.now(tz=timezone.utc)
print(f"Local time {now_local.isoformat(timespec='seconds')}")
print(f"UTC {now_UTC.isoformat(timespec='seconds')}")
# Local time 2021-03-26T16:09:18+01:00 # I'm on Europe/Berlin
# UTC 2021-03-26T15:09:18+00:00
Note: there's a deprecation shim for pytz.
older versions of Python 3: you can either use zoneinfo via the backports module or use dateutil instead. dateutil's tz.gettz follows the same semantics as zoneinfo.ZoneInfo:
from dateutil.tz import gettz
now_Israel = datetime.now(gettz('Israel'))
now_Pacific = datetime.now(gettz('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00
One way, through the timezone setting of the C library, is
>>> cur=time.time()
>>> os.environ["TZ"]="US/Pacific"
>>> time.tzset()
>>> time.strftime("%T %Z", time.localtime(cur))
'03:09:51 PDT'
>>> os.environ["TZ"]="GMT"
>>> time.strftime("%T %Z", time.localtime(cur))
'10:09:51 GMT'
The shortest ans of the question can be like:
from datetime import datetime
import pytz
print(datetime.now(pytz.timezone('Asia/Kolkata')))
This will print:
2019-06-20 12:48:56.862291+05:30
This script which makes use of the pytz and datetime modules is structured as requested:
#!/usr/bin/env python3
import pytz
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc)
PST = pytz.timezone("US/Pacific")
IST = pytz.timezone("Asia/Jerusalem")
print("UTC time {}".format(utc_dt.isoformat()))
print("Local time {}".format(utc_dt.astimezone().isoformat()))
print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Israeli time {}".format(utc_dt.astimezone(IST).isoformat()))
It outputs the following:
$ ./timezones.py
UTC time 2019-02-23T01:09:51.452247+00:00
Local time 2019-02-23T14:09:51.452247+13:00
Pacific time 2019-02-22T17:09:51.452247-08:00
Israeli time 2019-02-23T03:09:51.452247+02:00
This is my implementation:
from datetime import datetime
from pytz import timezone
def local_time(zone='Asia/Jerusalem'):
other_zone = timezone(zone)
other_zone_time = datetime.now(other_zone)
return other_zone_time.strftime('%T')
Can specify timezone by importing the modules datetime from datetime and pytx.
from datetime import datetime
import pytz
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))
tz_India = pytz.timezone('Asia/Kolkata')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))
If you want a method which doesn't require importing pytz or any specific timezone libraries, you can do it in this way which only imports datetime. By using datetime to get the current UTC time then adding the timezone modifier, any desired timezone can be achieved.
For example, the timezone in New York is 4 hours behind UTC time, or UTC-04:00.
This means we can use this code to find the current time in New York:
import datetime
utc_time = datetime.datetime.utc(now)
tz_modifier = datetime.datetime.timedelta(hours=-4)
tz_time = utc_time + tz_modifier
print(tz_time)
To make this more "elegant" as was wanted, this method could be used:
from datetime import datetime, timedelta
utc = datetime.utcnow()
print("China time {}".format(utc+timedelta(hours=8)))
print("Greece time {}".format(utc+timedelta(hours=3)))
print("Hawaii time {}".format(utc+timedelta(hours=-10)))
The downside to this method is that the actual UTC differences of the timezones must be known already.
I need time info all time time, so I have this neat .py script on my server that lets me just select and deselect what time zones I want to display in order of east->west.
It prints like this:
Australia/Sydney : 2016-02-09 03:52:29 AEDT+1100
Asia/Singapore : 2016-02-09 00:52:29 SGT+0800
Asia/Hong_Kong : 2016-02-09 00:52:29 HKT+0800
EET : 2016-02-08 18:52:29 EET+0200
CET : 2016-02-08 17:52:29 CET+0100 <- you are HERE
UTC : 2016-02-08 16:52:29 UTC+0000
Europe/London : 2016-02-08 16:52:29 GMT+0000
America/New_York : 2016-02-08 11:52:29 EST-0500
America/Los_Angeles : 2016-02-08 08:52:29 PST-0800
Here source code is one .py file on my github here:
https://github.com/SpiRaiL/timezone
Or the direct file link:
https://raw.githubusercontent.com/SpiRaiL/timezone/master/timezone.py
In the file is a list like this:
Just put a 'p' in the places you want printed.
Put a 'h' for your own time zone if you want it specially marked.
(' ','America/Adak'), (' ','Africa/Abidjan'), (' ','Atlantic/Azores'), (' ','GB'),
(' ','America/Anchorage'), (' ','Africa/Accra'), (' ','Atlantic/Bermuda'), (' ','GB-Eire'),
(' ','America/Anguilla'), (' ','Africa/Addis_Ababa'), (' ','Atlantic/Canary'), (' ','GMT'),
(' ','America/Antigua'), (' ','Africa/Algiers'), (' ','Atlantic/Cape_Verde'), (' ','GMT+0'),
(' ','America/Araguaina'), (' ','Africa/Asmara'), (' ','Atlantic/Faeroe'), (' ','GMT-0'),
(' ','America/Argentina/Buenos_Aires'), (' ','Africa/Asmera'), (' ','Atlantic/Faroe'), (' ','GMT0'),
(' ','America/Argentina/Catamarca'), (' ','Africa/Bamako'), (' ','Atlantic/Jan_Mayen'), (' ','Greenwich'),
(' ','America/Argentina/ComodRivadavia'), (' ','Africa/Bangui'), (' ','Atlantic/Madeira'), (' ','HST'),
(' ','America/Argentina/Cordoba'), (' ','Africa/Banjul'), (' ','Atlantic/Reykjavik'), (' ','Hongkong'),
I end up using pandas a lot in my code, and don't like importing extra libraries if I don't have to, so here's a solution I'm using that's simple and clean:
import pandas as pd
t = pd.Timestamp.now('UTC') #pull UTC time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_UTC_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format
t = pd.Timestamp.now(tz='US/Eastern') #pull Eastern (EDT or EST, as current) time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_EAST_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format
print(f"The current UTC time is: {now_UTC_rounded} (rounded to the nearest 10 min)")
print(f"The current US/Eastern time is: {now_EAST_rounded} (rounded to the nearest 10 min)")
Outputs:
The current UTC time is: 1800 (rounded to the nearest 10 min)
The current US/Eastern time is: 1400 (rounded to the nearest 10 min)
(actual Eastern time was 14:03)
The rounding feature is nice because if you're trying to trigger something at a specific time, like on the hour, you can miss by 4 minutes on either side and still get a match.
Just showing off features - obviously you don't need to use the round if you don't want!
You can check this question.
Or try using pytz. Here you can find an installation guide with some usage examples.

Get time zone information of the system in Python?

I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.
This should work:
import time
time.tzname
time.tzname returns a tuple of two strings: The first is the name of the local non-DST timezone, the second is the name of the local DST timezone.
Example return: ('MST', 'MDT')
Gives a UTC offset like in ThomasH's answer, but takes daylight savings into account.
>>> import time
>>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
>>> offset / 60 / 60 * -1
-9
The value of time.timezone or time.altzone is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actually like it, hence the * -1.
time.localtime().tm_isdst will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).
EDIT: marr75 is correct, I've edited the answer accordingly.
I found this to work well:
import datetime
tz_string = datetime.datetime.now(datetime.timezone.utc).astimezone().tzname()
For me this was able to differentiate between daylight savings and not.
From Python 3.6 you can do:
tz_string = datetime.datetime.now().astimezone().tzname()
Or
tz_string = datetime.datetime.now().astimezone().tzinfo
Reference with more detail: https://stackoverflow.com/a/39079819/4549682
Check out the Python Time Module.
from time import gmtime, strftime
print(strftime("%z", gmtime()))
Pacific Standard Time
The code snippets for calculating offset are incorrect, see http://bugs.python.org/issue7229.
The correct way to handle this is:
def local_time_offset(t=None):
"""Return offset of local zone from GMT, either at present or at time t."""
# python2.3 localtime() can't take None
if t is None:
t = time.time()
if time.localtime(t).tm_isdst and time.daylight:
return -time.altzone
else:
return -time.timezone
This is in all likelihood, not the exact question that the OP asked, but there are two incorrect snippets on the page and time bugs suck to track down and fix.
For Python 3.6+ this can be easily achieved by following code:
import datetime
local_timezone = datetime.datetime.utcnow().astimezone().tzinfo
print(local_timezone)
But with Python < 3.6 calling astimezone() on naive datetime doesn't work. So we've to do it in a slightly different way.
So for Python 3.x,
import datetime
local_timezone = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
print(local_timezone)
Sample Output:
On Netherlands Server(Python 3.6.9):
CEST
On Bangladesh Server(Python 3.8.2):
+06
More details can be found on this thread.
To obtain timezone information in the form of a datetime.tzinfo object, use dateutil.tz.tzlocal():
from dateutil import tz
myTimeZone = tz.tzlocal()
This object can be used in the tz parameter of datetime.datetime.now():
from datetime import datetime
from dateutil import tz
localisedDatetime = datetime.now(tz = tz.tzlocal())
or the tz parameter of datetime object via datetime.datetime.astimezone():
from datetime import datetime
from dateutil import tz
unlocalisedDatetime = datetime.now()
localisedDatetime = unlocalisedDatetime.astimezone(tz = tz.tzlocal())
Getting offset from UTC as timedelta:
from datetime import datetime, timezone
now = datetime.now()
now.replace(tzinfo=timezone.utc) - now.astimezone(timezone.utc)
Or like this (more obscure but also works):
datetime.now(timezone.utc).astimezone().tzinfo.utcoffset(None)
Both solutions give the same result. For example: datetime.timedelta(seconds=7200)
import tzlocal
tz_info = tzlocal.get_localzone() # 'US/Central' or 'Asia/Calcutta'
dt = datetime.now() # 2023-01-15 15:17:24.412430
print(tz_info.localize(dt) # 2023-01-15 15:17:24.412430-06:00
with tzlocal we will be able to get the local timezone.

Categories

Resources