Python convert raw GMT to othertime zone e.g SGT - python

I am trying to convert from GMT to e.g SGT:
For example, the value
0348 GMT should be 11:48 am
1059 GMT should be 6:59 pm
how do i do this?
i have tried:
date="03:48"
curr = (
dt.datetime.strptime(date, "%H:%M")
.astimezone(timezone('Asia/Singapore'))
)
print(curr)
But I am getting OSError: [Errno 22] Invalid argument

Assuming you have a naive datetime object which represents UTC:
from datetime import datetime, timezone
from dateutil import tz
now = datetime.now()
print(repr(now))
>>> datetime.datetime(2020, 7, 28, 8, 5, 42, 553781)
Make sure to set the tzinfo property to UTC using replace:
now_utc_aware = now.replace(tzinfo=timezone.utc)
print(repr(now_utc_aware))
>>> datetime.datetime(2020, 7, 28, 8, 5, 42, 553781, tzinfo=datetime.timezone.utc)
Now you can convert to another timezone using astimezone:
now_sgt = now_utc_aware.astimezone(tz.gettz('Asia/Singapore'))
print(repr(now_sgt))
>>> datetime.datetime(2020, 7, 28, 16, 5, 42, 553781, tzinfo=tzfile('Singapore'))
Sidenote, referring to your other question, if you parse correctly, you already get an aware datetime object:
date = "2020-07-27T16:38:20Z"
dtobj = datetime.fromisoformat(date.replace('Z', '+00:00'))
print(repr(dtobj))
>>> datetime.datetime(2020, 7, 27, 16, 38, 20, tzinfo=datetime.timezone.utc)

Related

Date format for year/month/date'T'/hour/minute/second/timezone in Python

In Python I would like to turn my str to time object and I am receiving an error.
ValueError: time data '2022-04-13T09:52:49-04:00' does not match format
What format should I use here?
Thanks
Try:
>>> datetime.strptime('2022-04-13T09:52:49-04:00',"%Y-%m-%dT%H:%M:%S%z")
datetime.datetime(2022, 4, 13, 9, 52, 49, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
ISO 8601 format was used, so it is task for datetime.datetime.fromisoformat
import datetime
d = '2022-04-13T09:52:49-04:00'
dt = datetime.datetime.fromisoformat(d)
print(repr(dt))
output
datetime.datetime(2022, 4, 13, 9, 52, 49, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

Changing string to UTC to dateTime object

I have time = '2020-06-24T13:30:00-04:00'. How can I change it to a dateTime object in UTC time. I would prefer not to use pd.Timestamp(time).tz_convert("UTC").to_pydatetime() because it returns a weird output that would look like this datetime.datetime(2020, 6, 24, 17, 30, tzinfo=<UTC>). As a result, when I check for equality with datetime.datetime(2020, 6, 24, 17, 30), it return False.
Edit:
import datetime
import pytz
time = '2020-06-24T13:30:00-04:00
dt = datetime.datetime(2020, 6, 24, 17, 30)
print("dt: ",dt)
so = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S%z').astimezone(pytz.utc)
print("so:",so)
print(dt == so)
outputs
dt: 2020-06-24 17:30:00
so: 2020-06-24 17:30:00+00:00
False
How can I get it to properly evaluate to True?
#1 Since your string is ISO 8601 compatible, use fromisoformat() on Python 3.7+:
from datetime import datetime, timezone
s = '2020-06-24T13:30:00-04:00'
dtobj = datetime.fromisoformat(s)
# dtobj
# datetime.datetime(2020, 6, 24, 13, 30, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
Note that this will give you a timezone-aware datetime object; the tzinfo property is a UTC offset. You can easily convert that to UTC using astimezone():
dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)
#2 You can achieve the same with strptime (also Python3.7+ according to this):
dtobj = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S%z')
dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)
#3 If you want to turn the result into a naive datetime object, i.e. remove the tzinfo property, replace with None:
dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)
#4 For older Python versions, you should be able to use dateutil's parser:
from dateutil import parser
dtobj = parser.parse(s)
dtobj_utc = dtobj.astimezone(timezone.utc)
dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)
Alright so my previous answer was sort of wack because I did not understand your issue entirely so I am rewriting it. You problem is that you are constructing a datetime object from a string and it is timezone aware(UTC). However, whenever you make a datetime object in python, dt = datetime.datetime(2020, 6, 24, 17, 30), it is creating it but with no timezone information (which you can check using .tzinfo on it). All you would need to do is make dt timezone aware when you first create it. See below my code snippit.
import datetime
time = '2020-06-24T13:30:00-04:00'
dt = datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)
print("dt: ",dt.tzinfo)
so = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S%z')
print("so:",so.tzinfo)
print(dt == so)

Parsing date, time and zone to UTC datetime object

As part of a logging system, I would like to parse a string timestamp coming from a Cisco device, which has the following format:
# show clock
16:26:19.990 GMT+1 Wed Sep 11 2013
The parsing result should be a UTC datetime instance which will be stored in a SQLite database, thus the need for a timezone conversion.
Using just datetime.strptime is not enough, because the %Z directive only recognises local timezones (i.e. those related to the current $LANG or $LC_* environment). Therefore, I need to make use of the pytz package.
Because the format is always the same, I can do something like the following:
import pytz
from datetime import datetime
s = '16:26:19.990 CEST Wed Sep 11 2013'
tm, tz, dt = s.split(" ", 2)
naive = datetime.strptime("%s %s" % (tm, dt), "%H:%M:%S.%f %a %b %d %Y")
aware = naive.replace(timezone=pytz.timezone(tz))
universal = aware.astimezone(pytz.UTC)
This, however, does not work without some modifications. The value of tz must be corrected to a name that is recognized by pytz. In the example, pytz.timezone('CEST') raises an UnknownTimezoneError because the real timezone is CET. The problem is that the daylight savings correction is not applied then:
>>> from datetime import datetime
>>> from pytz import UTC, timezone
>>> a = datetime.strptime('16:18:57.925 Wed Sep 11 2013', '%H:%M:%S.%f %a %b %d %Y')
>>> b = a.replace(tzinfo=timezone('CET'))
>>> a
datetime.datetime(2013, 9, 11, 16, 18, 57, 925000)
>>> b
datetime.datetime(2013, 9, 11, 16, 18, 57, 925000, tzinfo=<DstTzInfo 'CET' CET+1:00:00 STD>)
>>> b.astimezone(UTC)
datetime.datetime(2013, 9, 11, 15, 18, 57, 925000, tzinfo=<UTC>)
Using normalize does not seem to help:
>>> timezone('CET').normalize(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/etanol/virtualenvs/plexus/local/lib/python2.7/site-packages/pytz/tzinfo.py", line 235, in normalize
raise ValueError('Naive time - no tzinfo set')
ValueError: Naive time - no tzinfo set
>>> timezone('CET').normalize(b)
datetime.datetime(2013, 9, 11, 17, 18, 57, 925000, tzinfo=<DstTzInfo 'CET' CEST+2:00:00 DST>)
I don't really know what am I missing, but the wanted result is:
datetime.datetime(2013, 9, 11, 14, 18, 57, 925000, tzinfo=<UTC>)
Thanks in advance.
Using timezone.localize:
>>> from datetime import datetime
>>> from pytz import UTC, timezone
>>>
>>> CET = timezone('CET')
>>>
>>> a = datetime.strptime('16:18:57.925 Wed Sep 11 2013', '%H:%M:%S.%f %a %b %d %Y')
>>> print CET.localize(a).astimezone(UTC)
2013-09-11 14:18:57.925000+00:00

How to convert timezone in Django app

How can I change a timezone in a datetimefield.
right now I have
datetime.datetime(2013, 7, 16, 4, 30, tzinfo=<UTC>)
how can modify the tzinfo just for display not to update on the db.
Use pytz for such things.
From the pytz docs, you can use astimezone() to transform time into different time zone, as example below.
>>> eastern = timezone('US/Eastern')
>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
>>> loc_dt = utc_dt.astimezone(eastern)
>>> loc_dt.strftime(fmt)
'2002-10-27 01:00:00 EST-0500'

Parsing datetime in Python..?

I have a system (developed in Python) that accepts datetime as string in VARIOUS formats and i have to parse them..Currently datetime string formats are :
Fri Sep 25 18:09:49 -0500 2009
2008-06-29T00:42:18.000Z
2011-07-16T21:46:39Z
1294989360
Now i want a generic parser that can convert any of these datetime formats in appropriate datetime object...
Otherwise, i have to go with parsing them individually. So please also provide method for parsing them individually (if there is no generic parser)..!!
As #TimPietzcker suggested, the dateutil package is the way to go, it handles the first 3 formats correctly and automatically:
>>> from dateutil.parser import parse
>>> parse("Fri Sep 25 18:09:49 -0500 2009")
datetime.datetime(2009, 9, 25, 18, 9, 49, tzinfo=tzoffset(None, -18000))
>>> parse("2008-06-29T00:42:18.000Z")
datetime.datetime(2008, 6, 29, 0, 42, 18, tzinfo=tzutc())
>>> parse("2011-07-16T21:46:39Z")
datetime.datetime(2011, 7, 16, 21, 46, 39, tzinfo=tzutc())
The unixtime format it seems to hiccough on, but luckily the standard datetime.datetime is up for the task:
>>> from datetime import datetime
>>> datetime.utcfromtimestamp(float("1294989360"))
datetime.datetime(2011, 1, 14, 7, 16)
It is rather easy to make a function out of this that handles all 4 formats:
from dateutil.parser import parse
from datetime import datetime
def parse_time(s):
try:
ret = parse(s)
except ValueError:
ret = datetime.utcfromtimestamp(s)
return ret
You should look into the dateutil package.

Categories

Resources