Convert UTC+0 to other time zone Python - python

I have a time string obtained from API, it's UTC+0. I would like to change to other time zone.
I have tried below but it doesn't work. Could you please give me some idea ? many thanks.
utc0time='2021-04-17T15:50:14.614646+00:00'
dt = datetime.strptime('utc0time', '%Y-%m-%dT%H:%M:%S%z'). #it results as an error, not match the format
time.mktime(dt.timetuple())
calendar.timegm(dt.timetuple())

You could actually use timedelta in datetime module to +/- number of hours to achieve the time in other timezone you wish.
Here is an example where you can use timedelta:
https://www.geeksforgeeks.org/python-datetime-timedelta-function/

thanks for the comments and it gave me the idea. Because i only need to convert from one time zone to another one, i don't need to convert to multi-timezone. I don't use pytz this time. I used a silly method, changed the str to timestamp first, then used timedelta to adjust the hours. Below is my final code.
utc0time='2021-04-17T15:50:14.614646+00:00'
utc0time = utc0time[:-13]
timestamp = time.mktime(time.strptime(utc0time, '%Y-%m-%dT%H:%M:%S'))
datatimeformat = datetime.fromtimestamp(timestamp)
utc8time = datatimeformat + timedelta(hours = 8)

Related

convert H:MM:SS to iso

so i am taking the difference between two times (2022-07-20 23:10:00.990000) and 2022-07-20 23:10:02.100000. that gives me back 0:00:01.110000. i want that to transform to HH:MM:SS without the microseconds. the easiest way to take off microseconds is to do "avg_inqueue_time = str(avg_inqueue_time).split(".")[0]" that will give me 0:00:01. then i try to do avg_inqueue_time_transformed = datetime.strptime('%H:%M:%S', avg_inqueue_time) but gives an error ValueError: time data '%H:%M:%S' does not match format '0:02:07'.
any ideas how to transform that?
I believe a fast approach is to take a different time delta object where you only pick the seconds.
import datetime
time_1 = datetime.datetime(2022,7,20,23,10,00,990000)
time_2 = datetime.datetime(2022,7,20,23,10,2,100000)
timediff=(time_2-time_1)
timediff_wo_microseconds = datetime.timedelta(days=timediff.days, seconds=timediff.seconds)
print(timediff_wo_microseconds)

Converting a datetime to local time based on timezone in Python3

I have a question related to dates and time in Python.
Problem:
date = datetime.datetime.strptime(str(row[1]), "%Y-%m-%d %H:%M:%S")
localtime = date.astimezone(pytz.timezone("Europe/Brussels"))
formattedDate = localtime.strftime("%Y-%m%-%d")
In the code above, str(row[1]) gives back a UTC datetime coming from a mysql database: 2022-02-28 23:00:00
I parse this as a datetime and change the timezone to Europe/Brussels.
I then format it back to a string.
Expected result:
I'd like to return the date in local time. Europe/Brussels adds one hour so I would expect that strftime returns 2022-03-01, but it keeps returning 2022-02-28.
Can somebody help?
date is a naïve date, without timezone, because no timezone information was in the string you parsed. Using astimezone on that simply attaches timezone information to it, turning a naïve date into an aware one. It obviously can't convert any times, because it doesn't know what to convert from.
This also already contains the answer: make the date aware that it's in UTC first before trying to convert it to a different timezone:
date = datetime.datetime.strptime(...).astimezone(datetime.timezone.utc)
Ah, I see!
I ended up doing this, basically the same as you mentioned:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Europe/Brussels')
utcdate = datetime.datetime.strptime(str(row[1]), "%Y-%m-%d %H:%M:%S")
utcdate = utcdate.replace(tzinfo=from_zone)
localdate = utcdate.astimezone(to_zone)
formattedLocalDate = localdate.strftime("%Y%m%d");
The naïve date gets UTC aware by the utcdate.replace(tzinfo=from_zone).
Thanks for helping!

Finding the format of my timestamp in Python

My time format is screwy, but it seemed workable, as a string with the following format:
'47:37:00'
I tried to set a variable where:
DT = '%H:%M:%S'
So I could find the difference between two times, but it's given me the following error:
ValueError: time data '47:37:00' does not match format '%H:%M:%S'
Is it possible there are more elements to my time stamps than I thought? Or that it's formatted in minutes/seconds/milliseconds? I can't seem to find documentation that would help me determine my time format so I could set DT and do arithmetic on it.
It's because you set 47 to %H, that is not a proper value.
Here is an example:
import datetime
dt = datetime.datetime.strptime('2016/07/28 12:37:00','%Y/%m/%d %H:%M:%S')
print dt
Output: 2016-07-28 12:37:00
You wrote "I can't seem to find documentation that would help me determine my time format so I could set DT and do arithmetic on it"
Try this: https://docs.python.org/3/library/datetime.html
Way down to the bottom.
And yes, when the %H is matched with 47, you get boom the error.

How to convert dateutil.relativedelta object to datetime.timedelta object?

How can I convert a dateutil.relativedelta object to a datetime.timedelta object?
e.g.,
# pip install python-dateutil
from dateutil.relativedelta import relativedelta
from datetime import timedelta
rel_delta = relativedelta(months=-2)
# How can I convert rel_delta to a timedelta object so that I can call total_seconds() ?
time_delta = ???(rel_delta)
time_delta.total_seconds() # call the timedelta.total_seconds() method
You can't, for one huge reason: They don't store the same information. datetime.timedelta only stores days, seconds, and milliseconds, whereas dateutil.relativedelta stores every single time component fed to it.
That dateutil.relativedelta does so is important for storing things such as a difference of 1 month, but since the length of a month can vary this means that there is no way at all to express the same thing in datetime.timedelta.
In case someone is looking to convert a relativedelta to a timedelta from a specific date, simply add and subtract the known time:
utcnow = datetime.utcnow()
rel_delta = relativedelta(months=-2)
time_delta = utcnow + rel_delta - utcnow # e.g, datetime.timedelta(days=-62)
As a commenter points out, the resulting timedelta value will differ based on what month it is.
Depending on why you want to call total_seconds, it may be possible to refactor your code to avoid the conversion altogether. For example, consider a check on whether or not a user is over 18 years old:
datetime.date.today() - user['dateOfBirth'] < datetime.timedelta(days=365*18)
This check is not a good idea, because the timedelta object does not account for things like leap years. It's tempting to rewrite as:
datetime.date.today() - user['dateOfBirth'] < dateutil.relativedelta.relativedelta(years=18)
which would require comparing a timedelta (LHS) to a relativedelta (RHS), or converting one to the other. However, you can refactor the check to avoid this conversion altogether:
user['dateOfBirth'] + dateutil.relativedelta.relativedelta(years=18) > datetime.date.today()

Compare only time part in datetime - Python

I want to compare only time part in datetime. I have different dates with only time field to compare. Since dates are different and only time part i want to consider So i think creating two datetime object will not help.
my string as
start="22:00:00"
End="03:00:00"
Tocompare="23:30:00"
Above are strings when i convert them with datetime as
dt=datetime.strptime(start,"%H:%M:%S")
it gives
1900-01-01 22:00:00
which is default date in python.
So i need to avoid all this and want only time part. I simply need to check does my Tocompare falls between start and End
Just call the .time() method of the datetime objects to get their hours, minutes, seconds and microseconds.
dt = datetime.strptime(start,"%H:%M:%S").time()
Compare their times using datetime.time().
import datetime
start = datetime.datetime.strptime(start, '%H:%M:%S')
start = datetime.time(start.hour, start.minute,start.second)
tocompare = datetime.datetime.strptime(tocompare, '%H:%M:%S')
tocompare = datetime.time(tocompare.hour, tocompare.minute, tocompare.second)
start > tocompare # False

Categories