Python3 create a UTC date from string [duplicate] - python-3.x

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 3 years ago.
I have an API response which returns a date time object in String. I need to convert it into a UTC Datetime object to compare with the current datetime.
How do I convert this to an UTC DateTime object?
received "2019-03-22T06:35:57Z"

Parse the string and convert to datetime using strptime.
import datetime
dateob = datetime.datetime.strptime ("2019-03-22T06:35:57Z", "%Y-%m-%dT%H:%M:%SZ")
To convert to UTC:
>>> def Local2UTC(LocalTime):
... EpochSecond = time.mktime(LocalTime.timetuple())
... utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)
... return utcTime

Related

How to convert time object to datetime object in python? [duplicate]

This question already has answers here:
How do you convert a time.struct_time object into a datetime object?
(3 answers)
Closed 12 months ago.
I have timestamp which is a time object and trying to convert it to a datetime object because datetime has stonger capabilities and I need to use some function that only datetime has.
The reason I'm starting with time is because datetime doesn't support milliseconds which the original string contains.
What is the easiest way to do it?
assuming timestamp is an time object and datetimestamp will be the datetime object:
from datetime import datetime
import time
timestamp = time.strptime('2022-03-02 02:45:12.123', '%Y-%m-%d %H:%M:%S.%f')
datetimestamp = datetime(*timestamp[:5])
It works because time is actually a tuple with the following structure (year, month, day, hour, minute, seconds....), and the datetime __init__ expects the same sequence of variables

Convert date and time from UTC to local in specifed format

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(' ')

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.

Resources