facing difficulties converting utc timezone to local - python

I am getting date and time like this
date_time = "2022-02-17 08:29:36.345374"
And to convert these to AM, PM format I am doing something like this
date_formate = datetime.fromisoformat(date_time).strftime('%d/%m/%Y %I:%M %p')
but End time I am getting is in not local time seems it's in UTC , I am trying to convert it in utc but no luck doing something like this
dtUTC = datetime.fromisoformat(date_formate[:-1])
dtZone = dtUTC.astimezone()
print(dtZone.isoformat(timespec='seconds'))
got this solution on stackoverflow but getting error Invalid isoformat string: '2022-02-17 08:29:36.345374'

Python assumes local time by default if you don't specify a time zone / UTC offset. So in this case, you need to set UTC first, then convert, then format (if you want a string as output):
from datetime import datetime, timezone
date_time = "2022-02-17 08:29:36.345374" # UTC is not specified here...
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone()
print(local) # my tz was on UTC+1 at that date...
# 2022-02-17 09:29:36.345374+01:00
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM
If astimezone(None) does not work, you can try tzlocal;
import tzlocal
zone = tzlocal.get_localzone()
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM
or derive a timezone object from a timedelta, e.g.
from datetime import timedelta
zone = timezone(timedelta(minutes=-300)) # UTC-5 hours
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 03:29 AM

Related

converting time given from user input to utc

I want to convert a time given from user to UTC/RFC 3339 format.
For example, if they gave the string 2022-07-20 1:09:51 I want it to print it 2022-07-20T20:08:51Z. I got how to do it if given the posix time but dont understand how to do it given a string in the above format
Users in pacific time zone
Parse the input, set the timezone, convert to UTC, then format the output.
from datetime import datetime
from zoneinfo import ZoneInfo
# May need to "pip install tzdata" for latest timezone support.
# It is used by ZoneInfo. See https://docs.python.org/3/library/zoneinfo.html
UTC = ZoneInfo('UTC')
LOCAL = ZoneInfo('US/Pacific')
s = '2022-07-20 1:09:51'
dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
local = dt.replace(tzinfo=LOCAL)
utc = local.astimezone(UTC)
print('naive ',dt)
print('local ',local)
print('UTC ',utc)
print('ISO ',utc.isoformat())
print('custom',utc.strftime('%Y-%m-%dT%H:%M:%SZ'))
Output:
naive 2022-07-20 01:09:51
local 2022-07-20 01:09:51-07:00
UTC 2022-07-20 08:09:51+00:00
ISO 2022-07-20T08:09:51+00:00
custom 2022-07-20T08:09:51Z
If you want PM as you implied use either:
s = '2022-07-20 1:09:51pm'
dt = datetime.strptime(s, '%Y-%m-%d %I:%M:%S%p')
or
s = '2022-07-20 13:09:51'
dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
To get a final result of:
custom 2022-07-20T20:09:51Z

Subtract datetime in python, understanding formats

Given I have a timestamp:
date_time_str = '2019-09-10T13:48:06+0200'
How can I calculate the time difference between the current time and this datetime?
I've got it so far with an impression of strong wrongdoing - this should be possible in a far simpler way:
from datetime import datetime, timezone
import time
date_time_str = '2019-09-10T13:48:06+0200'
format = '%Y-%m-%dT%H:%M:%S%z'
date_time_obj = datetime.strptime(date_time_str, format)
now = datetime.now()
now_time = now.strftime(format)
print(now_time)
now=datetime.strptime(datetime.fromtimestamp(int(time.time()), tz=timezone.utc).isoformat(), format)
print("now is: %s" % now)
print(now-time_obj)
The above program does not work because the current time comes out in a slightly different formatting:
'2019-09-10T15:56:11+00:00'
That is, if you run the above script for example Python 3.6.5, you get the error:
ValueError: time data '2019-09-10T18:18:09+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
The mismatch is in the timezone format, "+00:00" vs. "+0200".
You can use datetime.now() to get the current datetime in utc:
# Same as your code
from datetime import datetime, timezone
date_time_str = '2019-09-10T13:48:06+0200'
format = '%Y-%m-%dT%H:%M:%S%z'
date_time_obj = datetime.strptime(date_time_str, format)
# Added:
print(datetime.now(tz=timezone.utc))
# 2019-09-10 18:35:48.066548+00:00
print(datetime.now(tz=timezone.utc) - date_time_obj)
# 6:47:42.066548

Python's datetime conversion

Here's my code:
from datetime import datetime
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
offset = datetime.now() - datetime.utcnow()
time_dt = datetime.strptime(time_str, '%d %b at %H:%M')
return (time_dt + offset).strftime('%I:%M %p')
What I'm having problems with is using a time_str that's only the time and doesn't include the day/month. ie: "02:00"
If I change it to: time_dt = datetime.strptime(time_str, '%H:%M') then I get an error about strftime and years before 1900.
So I'm stumped here. What needs done to allow just a time in the input string?
You can try with dateutil package. The parser.parse() method is good when your input string changes. It will construct a datetime object with todays date if only time is specified in the string. It will handle various other formats.
from datetime import datetime
from dateutil import parser
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
offset = datetime.now() - datetime.utcnow()
time_dt = parser.parse(time_str)
return (time_dt + offset).strftime('%I:%M %p')
If you are restricted to only datetime package you can do something like this:
from datetime import datetime
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
if len(time_str) <= 5:
time_str = datetime.now().strftime('%d %B at ') + time_str
offset = datetime.now() - datetime.utcnow()
time_dt = datetime.strptime(time_str, '%d %B at %H:%M')
return (time_dt + offset).strftime('%I:%M %p')
print get_local_time('27 March at 3:00')
print get_local_time('3:00')
Or you can do it like so:
from datetime import datetime
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
offset = datetime.now() - datetime.utcnow()
if len(time_str) <= 5:
time_dt = datetime.combine(datetime.now().date(), datetime.strptime(time_str, '%H:%M').time())
else:
time_dt = datetime.strptime(time_str, '%d %B at %H:%M')
return (time_dt + offset).strftime('%I:%M %p')
print get_local_time('27 March at 3:00')
print get_local_time('3:00')
I just tried it in the repl. It worked for me:
>>> from datetime import datetime
>>> time = "02:00"
>>> time_dt = datetime.strptime(time, '%H:%M')
>>> time_dt
datetime.datetime(1900, 1, 1, 2, 0)
>>>
If I remember right, a datetime can never store just a time, there will always be a dummy date of January 1, 1900. If you want to store the time without the dummy date, try using the time class. It also has a strftime function, see the docs here: https://docs.python.org/2/library/time.html
You could also try adding a different dummy date to your datetime if it isn't working.

converting local time to UTC time(datetime object)

I am trying to convert the local time to "UTC" time.
Followed this guide: How do I convert local time to UTC in Python?
But issue here is with the type of date which we giving here.
import pytz, datetime
local = pytz.timezone ("America/Los_Angeles")
naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone (pytz.utc)
In the above code input is "2001-2-3 10:11:12" (string), But in my case it will be a datetime object.
begin = begin.replace(hour=0, minute=0, second=0, microsecond=0)
Someone let me know how we can achieve the conversion here.
Your string format needs a bit of a modification. You just need the leading zeros in your month and day:
import pytz, datetime
local = pytz.timezone("America/Los_Angeles")
naive = datetime.datetime.strptime ("2001-02-03 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive)
utc_dt = local_dt.astimezone(pytz.utc)
If your input (begin) is not a time string but it is a naive (no timezone info) datetime object already then drop datetime.strptime() line (that parses the time string into datetime object) from the example. To convert a given naive datetime object that represents local time to utc:
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal
local_timezone = tzlocal.get_localzone()
local_dt = local_timezone.localize(begin, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)

Convert microseconds into format string with timezone

I need to convert a value in microseconds to the format '%Y-%m-%d %H:%M:%S' and apply timezone information to adjust the output. I tried:
datatime.datetime.fromtimestamp(timestamp).strftime('format')
but that is not timezone aware. How do I apply timezone information when converting from microseconds to a date and time string?
To convert the timestamp ("seconds since the epoch") to time in UTC as a naive datetime object:
#!/usr/bin/env python
from datetime import datetime
timestamp = 1422025533
utc_time = datetime.utcfromtimestamp(timestamp)
print("Time is = %s" % utc_time)
# -> Time is = 2015-01-23 15:05:33
If you want to get the value in a specific timezone as an aware datetime object; you should use pytz module:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
tz = pytz.timezone('Europe/London')
timestamp = 1422025533
london_time = datetime.fromtimestamp(timestamp, tz)
print("Time is = %s" % london_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# -> Time is = 2015-01-23 15:05:33 GMT+0000
I think Delorean is the right lib you should use.
Delorean is a library for clearing up the inconvenient truths that arise dealing with datetimes in
from datetime import datetime
from pytz import timezone
EST = "US/Eastern"
UTC = "UTC"
d = datetime.utcnow()
utc = timezone(UTC)
est = timezone(EST)
d = utc.localize(d)
d = est.normalize(d)
print d

Categories

Resources