Changing datetime format in py - python-3.x

I have the following code which gives the following output:
print(df1['Diff'].mean())
outputs:
10 days 16:13:29.467455
But since i just want the days value and not the time, i have done this:
print(datetime.strptime(df1['Diff'].mean(), format ='%d')
but i am getting the following error:
^
SyntaxError: unexpected EOF while parsing
Why am i getting this error?

For date, time, and datetime objects
You should be using strftime to format the time, not to parse the time (as in strptime).
print(obj.strftime('%d'))
strptime expects a string to be passed in (and you were passing in a datetime object), whereas strftime formats an existing datetime object.
For timedelta objects
print(obj.days)
This gets the days counterpart you're looking for.

I think the instance of df1['Diff'].mean() is str and datetime.strptime() can be use only in datetime methods. So to only get date you have to take slice of df1['Diff'].mean() like df1['Diff'].mean()[:-14]
Which is in your case.

Related

How to supress warning: Datetime with no tzinfo will be considered UTC?

I have the following code which am using to monitor Azure ADF pipeline runs. The code uses 'RunFilterParameters' to apply a date range filter in extracting run results:
filter_params = RunFilterParameters(last_updated_after=datetime.now() - timedelta(1), last_updated_before=datetime.now() + timedelta(1))
query_response = adf_client.activity_runs.query_by_pipeline_run(resource_group, adf_name, row.latest_runid,filter_params)
The above works ok, however it is throwing a warning:
Datetime with no tzinfo will be considered UTC
Not sure how to add timezone to this or just suppress the warning?
Please help.
"no tzinfo" means that naive datetime is used, i.e. datetime with no defined time zone. Since Python assumes local time by default for naive datetime, this can cause unexpected behavior.
In the code example given in the question, you can create an aware datetime object (with tz specified to be UTC) like
from datetime import datetime, timezone
# and use
datetime.now(timezone.utc)
If you need to use another time zone than UTC, have a look at zoneinfo (Python 3.9+ standard library).

Need Help Converting DateTime Using Python3

I have the follow code, but having trouble removing the Z at the end. The time format looks like this 2020-07-28T15:47:36.165310258Z
from datetime import datetime
datetime.strptime(f[a]['Created On'], "%Y-%m-%dT%H:%M:%S.%f")
When using the %f, I noticed that it is only able to the next 6 digit. Is there any way to make it take more? This is the error that I am getting (MISSING) ValueError: unconverted data remains: 258Z
What is the best way to remove the Z and have it just return the date?
Was able to get around the issue by just moving the last 4 characters from the string and then using datetime.strptime on it.
datetime.strptime(f[a]['Created On'][:-4], "%Y-%m-%dT%H:%M:%S.%f")

Given a datetime.time(X,Y) object, how to convert it to time string?

I am given the following object:
datetime.time(18, 50)
I want to convert to a string:
"18:50:00"
Please advise how can I do this?
Tried strftime but getting errors.
datetime.time(18, 50).strftime("%H:%M:%S")
You need to do:
from datetime import time
print(time(18, 50).strftime("%H:%M:%S"))
Importing the time function from datetime module seems to be different from datetime instance's time method.

How to parse specific date format with strptime?

I am using python3 and I have a time data format like '01-FEB-17' and I need to parse it with datetime.strptime. Does anyone know which format is the correct for this? I tried '%d-%b-%Y', '%d-%m-%Y',... and none of them worked.
Thanks
You can use this
from datetime import datetime
t = datetime.strptime('01-FEB-17', '%d-%b-%y')
NOTE: You can head here for a full list of format specifiers to use

Python timezone conversion adding minutes to the hour?

So I'm trying to convert a bunch of hours (10:00:00, 14:00:00, etc) from a given timezone to UTC.
When I do so, I keep maddeningly getting things back like "15:51:00".
When you get to that line, and print what value it's using, it's using something like:
1900-01-01 12:00:00-05:51
Which is fine, except for the -05:51 bit. I have no idea why that -05:51 is there, and it's causing me problems. UTC conversion is hour to hour, yes? I think it's got something to do with my timezone conversions, but I really don't get why they would be doing that.
Here's a minimal example that has the same erroneous output; it returns 15:51:00 when it should just return a flat hour, no minutes.
import datetime
from dateutil import tz
jj = datetime.datetime.strptime("10:00:00", "%H:%M:%S")
tzz = tz.gettz('US/Central')
def constructstring(tzz,x):
inter2 = x.replace(tzinfo=tzz) #ERROR HAPPENS HERE (I'm pretty sure anyways)
inter3 = inter2.astimezone(tz.tzutc())
return inter3
print(constructstring(tzz,jj).strftime("%H:%M:%S"))
You are not specifying a date when you create the jj datetime object, so the default date of 1900-01-01 is used. Timezones are not fixed entities; they change over time, and the US/Central timezone used a different offset back in 1900.
At the very least, use a recent date, like today for example:
# use today's date, with the time from jj, and a given timezone.
datetime.datetime.combine(datetime.date.today(), jj.time(), tzinfo=tzz)
If all you need is a time, then don't create datetime objects to store those; the datetime module has a dedicated time() object. I'd also not use strftime() to create objects from literals. Just use the constructor to pass in integers:
jj = datetime.time(10, 0, 0) # or just .time(10)
Other good rules of thumb: If you have to deal with dates with timezones, try to move those to datetime objects in UTC the moment your code receives or loads them. If you only have a time of day, but still need timezone support, attach them to today's date, so you get the right timezone. Only convert to strings again as late as possible.

Resources