I have the following datetime, and I converted to datetime object.
How do I convert it to say GMT+7 timezone?
date = "2020-07-27T16:38:20Z"
curr = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")
print(curr)
If converting to a timezone will work for you then you can convert it like this:
import datetime as dt
from pytz import timezone
date = "2020-07-27T16:38:20Z"
curr = (
dt.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")
.astimezone(timezone('US/Pacific'))
)
print(curr)
OUTPUT:
2020-07-27 09:38:20-07:00
You can list the available timezones like this:
from pytz import all_timezones
for tz in all_timezones:
print(tz)
You can use this code here:
import pytz
date = datetime(2020, 7, 27, 16, 38, 20)
local_time_zone = pytz.timezone('GMT+0')
Or you can get your local time zone
# from tzlocal import get_localzone
# local_time_zone = get_localzone()
def utc_to_local(date):
local_date = date.replace(tzinfo=pytz.utc).astimezone(local_time_zone)
return local_time_zone.normalize(local_date)
print(utc_to_local(date).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z'))
print(utc_to_local(datetime.utcnow()).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z'))
The output will be like this:
2020-07-27 16:38:20.000000 GMT+0000
2020-07-28 13:31:23.219703 GMT+0000
Related
i create this loop to give all timezones :
import datetime
import pytz
today=datetime.datetime.now(tz=pytz.UTC)
for i in pytz.all_timezones:
print(today.astimezone(pytz.timezone(i)))
but i want to get them in order from -9 to +14
now = datetime.datetime.now()
tzs = sorted(pytz.all_timezones, key=lambda tz: pytz.timezone(tz).utcoffset(now))
This gives you a list like:
['Etc/GMT+12',
'Etc/GMT+11',
'Pacific/Midway',
'Pacific/Niue',
'Pacific/Pago_Pago',
'Pacific/Samoa',
'US/Samoa',
'Etc/GMT+10',
'HST',
'Pacific/Honolulu',
...]
Supposing you are just interested in GMT timezones...
from datetime import datetime
from pytz import UTC, all_timezones, timezone, UnknownTimeZoneError
now = datetime.now(tz=UTC)
print('Timezones should be similar to these...')
timezones_candidates = [tz for tz in all_timezones if 'GMT' in tz]
print(timezones_candidates)
first = -14
last = +9
desired_timezones = ['Etc/GMT{0:+}'.format(shift) for shift in range(first, last+1)]
print('\nNow as timezone:')
for tz in desired_timezones:
try:
print(now.astimezone(timezone(tz)))
except UnknownTimeZoneError:
print('The timezone {0} doesnt exist'.format(tz))
import datetime
import pytz
today=datetime.datetime.now(tz=pytz.UTC)
ordered = {}
for i in pytz.all_timezones:
timezone = today.astimezone(pytz.timezone(i))
gmt = str(timezone)[-6:-3]
gmt = (-1 if gmt[0] == '-' else 1) * int(gmt[1:])
ordered[pytz.timezone(i)] = gmt
for timezone, _ in sorted(ordered.items(), key=lambda item: item[1]):
print(today.astimezone(timezone))
I have a time string, say
str = "2018-09-23 14:46:55"
and an offset
offset = "0530"
I want to get str2 with offset added, ie
str2 = "2018-09-23 20:16:55"
Please guide.
You can use the datetime module:
from datetime import datetime, timedelta
x = "2018-09-23 14:46:55"
offset = "0530"
res = datetime.strptime(x, '%Y-%m-%d %H:%M:%S') + \
timedelta(hours=int(offset[:2]), minutes=int(offset[2:]))
print(res)
datetime.datetime(2018, 9, 23, 20, 16, 55)
Use timedelta to add offset to a datetime object.
from datetime import datetime, timedelta
str = "2018-09-23 14:46:55"
str = datetime.strptime(str, "%Y-%m-%d %H:%M:%S")
str2 = str + timedelta(hours=5, minutes=30)
print(str2)
ex:
I have a date string
2018-02-17 16:15:36.519 PST
How do i convert into isoformat in UTC like below
2018-02-18T00:15:36.519Z
I tried this
from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
print parse(d1)
it prints like this. How do i convert it to UTC with Z at the end.
2018-02-17 16:15:36.519000-08:00
EDIT
using python 2.7.
import dateutil
import pytz
from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
d2=dateutil.parser.parse(d1)
d2.replace(tzinfo=pytz.utc) - d2.utcoffset()
d3=(d2.replace(tzinfo=pytz.utc) - d2.utcoffset()).isoformat()
print d3
then formatting with Z as suggested
To parse a time string with a timezone abbreviation (PST) into a timezone-aware datetime object:
import dateparser # pip install dateparser
pst_dt = dateparser.parse('2018-02-17 16:15:36.519 PST')
# -> datetime.datetime(2018, 2, 17, 16, 15, 36, 519000, tzinfo=<StaticTzInfo 'PST'>)
To convert the time to UTC timezone:
import datetime as DT
utc_dt = pst_dt.astimezone(DT.timezone.utc)
# -> datetime.datetime(2018, 2, 18, 0, 15, 36, 519000, tzinfo=datetime.timezone.utc)
To print it in the desired format:
print(utc_dt.isoformat()) # -> 2018-02-18T00:15:36.519000+00:00
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ')) # -> 2018-02-18T00:15:36.519000Z
On Python 2.7 there is no DT.timezone.utc:
utc_naive = psd_dt.replace(tzinfo=None) - psd_dt.utcoffset()
print utc_naive.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
# -> 2018-02-18T00:15:36.519000Z
Note: in the general case the timezone abbreviation (such as PST) may be ambiguous. See Parsing date/time string with timezone abbreviated name in Python?
In your specific case, the time string corresponds to unique UTC time:
>>> from collections import defaultdict
>>> import datetime as DT
>>> import pytz
>>> naive_dt, tzabbr = DT.datetime(2018, 2, 17, 16, 15, 36, 519000), 'PST'
>>> utc_times = defaultdict(list)
>>> for zone in pytz.all_timezones:
... dt = pytz.timezone(zone).localize(naive_dt, is_dst=None)
... if dt.tzname() == tzabbr: # same timezone abbreviation
... utc_times[dt.astimezone(pytz.utc)].append(zone)
>>> for utc_dt, timezones in utc_times.items():
... print(f'{utc_dt:%c %Z}', *timezones, sep='\n\t')
Sun Feb 18 00:15:36 2018 UTC
America/Dawson
America/Ensenada
America/Los_Angeles
America/Santa_Isabel
America/Tijuana
America/Vancouver
America/Whitehorse
Canada/Pacific
Canada/Yukon
Mexico/BajaNorte
PST8PDT
US/Pacific
US/Pacific-New
See linux convert time(for different timezones) to UTC
This is a demo code from python2.7, FYI, thanks!
from datetime import datetime
from pytz import utc, timezone
def get_current_pst_time():
print('------------(1) Current time to PST time----------------')
local_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
utc_time = datetime.now(tz=utc).strftime('%Y-%m-%d %H:%M:%S')
pst_time = datetime.now(tz=utc).astimezone(timezone('US/Pacific')).strftime('%Y-%m-%d %H:%M:%S')
is_summary_time = bool(datetime.now(tz=utc).astimezone(timezone('US/Pacific')).dst())
print('is it a summary time? %s.' % is_summary_time)
print('local time is %s.' % local_time)
print('utc time is %s.' % utc_time)
print('pst time is %s.' % pst_time)
def convert_pst_time_to_utc_time(pst_time_str):
print('------------(2) PST time to UTC time----------------')
print('pst time is %s.' % pst_time_str)
temp_time = datetime.strptime(pst_time_str, '%Y-%m-%d %H:%M:%S')
pacific_timezone = timezone('US/Pacific')
pst_time = pacific_timezone.localize(temp_time, is_dst=None)
assert pst_time.tzinfo is not None
assert pst_time.tzinfo.utcoffset(pst_time) is not None
is_summary_time = bool(pst_time.dst())
print('is it a summary time? %s.' % is_summary_time)
utc_time = pst_time.astimezone(timezone('utc'))
print('utc time is %s.' % utc_time.strftime('%Y-%m-%d %H:%M:%S'))
def convert_utc_time_to_pst_time(utc_time_str):
print('------------(3) UTC time to PST time----------------')
print('utc time is %s.' % utc_time_str)
temp_time = datetime.strptime(utc_time_str, '%Y-%m-%d %H:%M:%S')
utc_timezone = timezone('utc')
utc_time = utc_timezone.localize(temp_time, is_dst=None)
assert utc_time.tzinfo is not None
assert utc_time.tzinfo.utcoffset(utc_time) is not None
pst_time = utc_time.astimezone(timezone('US/Pacific'))
is_summary_time = bool(pst_time.dst())
print('is it a summary time? %s.' % is_summary_time)
print('pst time is %s.' % pst_time.strftime('%Y-%m-%d %H:%M:%S'))
if __name__ == '__main__':
get_current_pst_time()
convert_pst_time_to_utc_time('2019-12-03 02:00:00')
convert_pst_time_to_utc_time('2020-07-03 02:00:00')
convert_utc_time_to_pst_time('2019-12-03 10:00:00')
convert_utc_time_to_pst_time('2020-07-03 09:00:00')
If I run this url : https://api.sunrise-sunset.org/json?lat=12.98&lng=77.61&date=2017-08-26
I get sunrise time: "12:38:14 AM"
and this is UTC time, if I convert it to given timezone using :
from datetime import datetime
import pytz
from dateutil import tz
def convertUTCtoLocal(date, utcTime, timezone):
""" converts UTC time to given timezone
"""
to_zone = pytz.timezone(timezone)
from_zone = _tz.gettz('UTC')
utc = _datetime.strptime('%s %s' % (date, utcTime), '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
return str(local.time())
but this returns 18:08:16 which is evening time , so what am I doing wrong here.
given timzone is Asia/Kolkata
Example:
>>> from datetime import datetime
>>> from dateutil import tz
>>> from_zone = tz.gettz('UTC')
>>> to_zone = tz.gettz('Asia/Kolkata')
>>> utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
>>> utcTime = "12:38:16" ## from json URL we get AM/PM but I remove it.
>>> utc = datetime.strptime('2017-08-26 {}'.format(utcTime), '%Y-%m-%d %H:%M:%S')
>>> utc
datetime.datetime(2017, 8, 26, 12, 38, 16)
>>> utc = utc.replace(tzinfo=from_zone)
>>> central = utc.astimezone(to_zone)
>>> central
datetime.datetime(2017, 8, 26, 18, 8, 16, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Kolkata'))
The problem was that you had "12:38:16 AM" which is actual "00:38:16" so you can't just strip "AM". I changed your function so it will work with "AM" and "PM" hours, just don't strip "AM" and "PM" before using the function:
import pytz
from _datetime import datetime
from dateutil import tz
def convertUTCtoLocal(date, utcTime, timezone):
""" converts UTC time to given timezone
"""
to_zone = pytz.timezone(timezone)
from_zone = tz.gettz('UTC')
## for formating with AM and PM hours in strptime you need to add
## %p at the end, also instead of %H you need to use %I
utc = datetime.strptime('%s %s' % (date, utcTime), '%Y-%m-%d %I:%M:%S %p')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
return str(local.time())
date = '2017-08-26'
utcTime = '12:38:14 AM' ## Don't strip AM or PM
timezone = 'Asia/Kolkata'
x = convertUTCtoLocal(date, utcTime, timezone)
print(x)
Also, you can see working example here.
how can i convert my string of date to a datetime.timedelta() in Python?
I have this code :
import datetime
date_select = '2011-12-1'
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
thanks in advance ...
You wouldn't convert date_select to a timedelta, instead, you need a datetime object, which can be added to a timedelta to produce an updated datetime object:
from datetime import datetime, timedelta
date_select = datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
Or, if you prefer, without the fancy from ... import ... import line:
import datetime # <- LOOK HERE, same as in your example
date_select = datetime.datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
You use strptime to do this.
from datetime import datetime
target_date = datetime.strptime(date_select, '%Y-%m-%d')
from datetime import datetime, timedelta
date_select = '2011-12-1'
new_data = datetime.strptime(date_select, '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
You will get 2011-12-02 00:00:00; to strip off the '00:00:00' and get only the date, just add .date() to target_date
print target_date.date()
This should give you the only the date = 2011-12-02