Convert date and time from UTC to local in specifed format - python-3.x

I have UTC date time as 2021-02-24 12:41:40.
I want to get it converted into local timezone in 24 hour format i.e. "IST" in same format i.e. 2021-02-24 18:11:40.
I referred many answers on Stackoverflow, but I am not able to get the result in desired format.
How can it be achieved in Python3?

what I linked applied specifically to your question:
from datetime import datetime, timezone
from dateutil.tz import gettz
# the given info:
ist = gettz("Asia/Kolkata")
s = "2021-02-24 12:41:40"
# now parse to datetime and set tzinfo to UTC
dt = datetime.fromisoformat(s).replace(tzinfo=timezone.utc)
# convert to IST time zone
dt = dt.astimezone(ist)
# output to isoformat string, but without time zone info
s = dt.replace(tzinfo=None).isoformat(' ')
print(s)
# 2021-02-24 18:11:40

Solution for Python 3.6.*
datetime = "2021-02-24 12:41:40"
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
utc = datetime.strptime( datetime,'%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
localTime = local.replace(tzinfo=None).isoformat(' ')

Related

converting string date time with microseconds to date object

I have a datetime coming from json data as 2017-03-28T00:00:00.000Z
I have tried this
datetime.datetime.strptime(record_date, "%Y-%m-%d%H:%M:%S%f")
but this gives error:
*** ValueError: time data '2017-03-28T00:00:00.000Z' does not match format '%Y-%m-%d%H:%M:%S%f'
I have to compare the read date with user input date as 2017-03-28 format
Your time is in isoformat, you need to use datetime's fromisoformat to convert it into a datetime object.
The [:-1] is to exclude the Z because datetime does not understand what that is. (2017-03-28T00:00:00.000Z is actually RFC 3339)
Z basically means UTC timezone (+00:00 GMT)
from datetime import datetime
foo = "2017-03-28T00:00:00.000Z"
bar = datetime.fromisoformat(foo[:-1])
print(bar)
print(type(bar))
Gives you the result of, but this is now naive (unaware of timezone)
2017-03-28 00:00:00
<class 'datetime.datetime'>
A quick workaround to make it timezone aware is
bar = datetime.fromisoformat(foo.replace('Z', '+00:00'))
print(bar)
2017-03-28 00:00:00+00:00
#If milliseconds are of concern then just strftime
bar = datetime.fromisoformat(foo.replace('Z', '+00:00')).strftime("%Y-%m-%d %H:%M:%S:%f %Z")
# the Z displays UTC or equivalent time zone
2017-03-28 00:00:00:000000 UTC
The dateutil module is even better at handling this as it has native support for RFC 3339.
import dateutil.parser
foo = "2017-03-28T00:00:00.000Z"
bar = dateutil.parser.isoparse(foo)
print(bar)
print(type(bar))
2017-03-28 00:00:00+00:00
<class 'datetime.datetime'>

How to convert zulu datetime format to user defined time format

Hi I have this DateTime format in our log "2019-09-19T15:12:59.943Z"
I want to convert this to custom DateTime format 2019-09-19 15:12:59
from datetime import datetime
timestamp = "2019-09-19T15:12:59.943Z"
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))
which function shall I use for this
thanks
okay
This issue is related to custom DateTime formatting not related to timestamp.
because timestamp in python is an integer value, not a string value.
So you have a custom DateTime format which contains Zulu time format.
and you need to convert this Zulu DateTime format to custom DateTime format.
so, try this python script and its working fine on Python version 3.6
import datetime
d = datetime.datetime.strptime("2019-09-19T15:12:59.943Z","%Y-%m-%dT%H:%M:%S.%fZ")
new_format = "%Y-%m-%d"
d.strftime(new_format)
print(d)
or you can use this online fiddle to check the result
https://pyfiddle.io/fiddle/c7b8e849-c31a-41ba-8bc9-5436d6faa4e9/?i=true

How to convert a UTC date string to timezone aware datetime object in Python3?

I have a UTC format date string represented as :
ds = "2019-06-15 17:18:06 UTC"
I am trying to convert it into a python utc datetime object like this :
d = datetime.strptime(ds,'%Y-%m-%dT%H:%M:%SZ')
However I am getting the following error :
ValueError: time data '2019-06-15 17:18:06 UTC' does not match format '%Y-%m-%dT%H:%M:%SZ'
So what is the correct format to pass, so that I get a datetime object in UTC timezone?
Use format %Y-%m-%d %H:%M:%S %Z
Ex:
import datetime
import pytz
ds = "2019-06-15 17:18:06 UTC"
nDate = datetime.datetime.strptime(ds,'%Y-%m-%d %H:%M:%S %Z')
timezone = pytz.timezone(ds.split()[-1])
d_aware = timezone.localize(nDate)
print(d_aware)
print(d_aware.tzinfo)
Output:
2019-06-15 17:18:06+00:00
UTC
The format string you are currently using doesn't match with the datetime string format which you provided. That's why its throwing error.
datetime.strptime(ds,'%Y-%m-%d %H:%M:%S UTC')

convert string having timezone into to utc datetime object python

I have a timezone aware string like this and would like to convert it to utc timezone. I am using python 3.4 version
My string is like -
2018-05-04T05:22:52.3272611-04:00
I am not able to get much info on converting the given datetime to utc.
That looks like an ISO 8601 string (though with anomalously high precision on the sub-second component); if the fact that you have 7 digits instead of 6 after the decimal point is a typo, you can use dateutil.parser.isoparse on it:
from dateutil.parser import isoparse
from dateutil.tz import UTC
dt = isoparse('2018-05-04T05:22:52.327261-04:00')
dt.astimezone(UTC)
Otherwise you can use dateutil.parser.parse, which is slower but allows for more unusual formats:
from dateutil.parser import parse
from dateutil.tz import UTC
dt = parse('2018-05-04T05:22:52.3272611-04:00')
dt.astimezone(UTC)
You should also use parse if you are not certain what the format will be.

converting timestamp to datetime in python

I have a timestamp which is coming from a remote Linux box. This is the timestamp 1356354496.
When I am using the fromtimestamp function I am getting a different output then what it should be.
Example:
from datetime import datetime
import time
print(time.ctime(int("1356354496")))
cwStartTimeDisplay=datetime.fromtimestamp(int("1356354496")).strftime("%a %b %d %H:%M:%S %Y")
print(cwStartTimeDisplay)
Output
Mon Dec 24 05:08:16 2012
Mon Dec 24 05:08:16 2012
Whereas I should be getting 12/24/2012 6:38:16 PM. I am a beginner and don't really know if tz parameter is the answer to this. Can anybody help please?
Your timestamp seems to be UTC, so if you need id represented in IST, you need to convert it.
The recommended library to work with timezone data in python is pytz
from datetime import datetime
import pytz
ist = pytz.timezone("Asia/Kolkata")
utcdate = pytz.utc.localize(datetime.utcfromtimestamp(1356354496))
print("UTC:", utcdate)
istdate = ist.normalize(utcdate)
print("IST:", istdate)
# or shorter:
date = datetime.fromtimestamp(1356354496, ist)
print("IST:", date)
output:
UTC: 2012-12-24 13:08:16+00:00
IST: 2012-12-24 18:38:16+05:30
IST: 2012-12-24 18:38:16+05:30

Resources