Python tzinfo=pytz.utc on existing time - python

I have a variable current_time which is current date time formatted the way I need. I need to convert the time from completed_date to be in the same format. I thought the code below would work but it throws error - replace() takes no keyword arguments. I cant seem to figure out the corrent syntax for this for some reason.
current_time = datetime.utcnow().replace(tzinfo=pytz.utc) # code i use now
completed_date - 2019-12-07T15:17:04+00:00 # print of completed_date variable
completed_date = completed_date.replace(tzinfo=pytz.utc) # how I thought I could modify completed_date to look like current time

Related

How to force time in datetime field when saving a record in odoo?

In my odoo module, I have a datetime field (prefered_date). What I want to do is that, no matter what time the user enters, the time is always set at 10 am. I tried to do it with the following code. but is not working. The time is getting set to 6 am instead of 10. Maybe it has something to do with the timezone. What am I doing wrong?
#api.multi
def write(self, values):
if 'prefered_date' in values:
date = datetime.strptime(values.get('prefered_date'), '%Y-%m-%d %H:%M:%S')
newdate = date.replace(hour=10, minute=0)
new = newdate.strftime("%Y-%m-%d %H:%M:%S")
values['prefered_date'] = new
return super(PostabilidadRequest, self).write(values)
One thing I'm missing in your question is where you're seeing this 6 am value: do you see this in the browser, or in python?
I'm guessing you're seeing this value in the browser. Any date objects in the database are stored as UTC and the front-end will use the user's timezone to show the right (local) time. Could it be you are in a time zone that is in UTC-4? In that case a value of 10 am in your python code / database will show as 6 am in the browser.
What you can try is to enter 10 am as the value in the front-end and use a print(date) in your python code to see how this value is being received by your code. Then adjust this accordingly, so if you enter 10 am in the front-end and it turns into 6 am in the python code, you change your code to date.replace(hour=6, minute=0) to adjust for this time difference.
Do keep in mind this might give some odd results if you have users from different time zones as they won't all have a four hour offset.
As a unrelated side-note: the .get() function in values.get('preferred_date') is used to gracefully return None when the value does not exists (instead of throwing an exception). But as you already checked for the existence of the value (if 'preferred_date' in values) you know there will be some value there and you can safely use values['preferred_date'] directly.

Python: UTC vs local timestamp

Why the followings return different timestamp? Is it because datetime.utcnow() doesn't have a timezone? It looks to me that tzinfo=utc is redudant, so I am probably not getting what is utcnow() and how an UTC number could not have a timezone. I guess there is a reason, so please enlight me :)
from datetime import datetime
from pytz import utc
local_seconds = int(datetime.utcnow().timestamp())
utc_seconds = int(datetime.utcnow().replace(tzinfo=utc).timestamp())
My goal is to get the UTC timestamp. It looks like the first method returns the local timestamp (correct me if I am wrong)
EDIT:
Where I live the timezone is GMT-5. In fact:
(utc_seconds-local_seconds)/3600 # is equal to -5.0
Following two statements would always return different result.
local_seconds = int(datetime.utcnow().timestamp())
utc_seconds = int(datetime.utcnow().replace(tzinfo=utc).timestamp())
Output:
1585584790
1585604590
You ask why? Because, by the time first statement executes, there is some time spent during execution and now the second statement would fetch you different result because datetime.utcnow() for 2nd statement has changed.
What I assume is, you want to see if both operations would give the same result or not? They definitely would have given the same results :
Had you provided them the same input?
Had you performed the similar operation from a common library.
To solve 1. change your code like this.
same_time_input = datetime.utcnow()
local_seconds = int(same_time_input.timestamp())
utc_seconds = int(same_time_input.replace(tzinfo=utc).timestamp())
Still the output would not be same, because you are using an external library, and the replace function is not working as you expected.
If you printout the tzinfo from same_time_input, you would see that it doesn't have any timezone info reason of which can be read here. --> Why does datetime.datetime.utcnow() not contain timezone information?
print(same_time_input.tzinfo)
Now, you are trying to give it a timezone info using a separate library which has different implementation internally resulting in slightly off results.

Python - Timedelta to datetime with miliseconds -> "HH:MM:SS"

On this problem I keep getting stuck when trying several options provided.
In simple words, I'm running a script that has a starting time (several actually, based on different criteria) and in a loop I want to display the running time of that criteria in a JSON and put it in a program (using requests) that is updated every time the loop passes one of the criteria.
I was doing that by simply running:
starting_time = datetime.now() #but just a bit earlier in the script
now = datetime.now()
running_time = now-starting_time
This running_time is then used as a variable in a JSON, but that needs to be in the format of 'HH:MM:SS' else my requests doesn't allow me to put. Which caused the problem for me, because it isn't possible to use strftime on a timedelta.
The timedelta might be based on miliseconds, but those are fine as "00:00:00"... but that caused me problems when trying to convert the timedelta to string first and then convert it back to a regular datetime.
What am I missing?
A possible workaround would be:
starting_time = datetime.now()
now = datetime.now()
running_time = now-starting_time
x = datetime.timedelta(seconds=running_time.seconds)
result = str(x)
if result[1] == ":":
result = "0"+result
print(result)
Here line 4 makes sure that x only has the seconds and ignores the miliseconds of running_time. Then we add a zero at the beginning in case needed.
But also see comment to better understand timedelta.

Formatting a date and time with periods as separators

I am trying to apply current time and date in a Windows application using Python. I used the following code:
current_time = str(time.strftime("%m.%d.%Y %H:%M"))
type(waitForObject("{name='TextBoxSampleName'}"), "Test." + current_time)
but when I run the script I see the following format
27Test.06.03.2016 10 (the hours and minutes are separated for some reason)
I want the final result to be Test.06.03.2016.10:27
Without knowing what waitForObject is, we can still get the output you desire.
First, there is a minor formatting mistake in your current_time = line:
current_time = str(time.strftime("%m.%d.%Y.%H:%M"))
^-- Add this period to get the format you want
Next, the second line can simply be (or you can assign it to a variable for later use):
print("Test."+current_time)
These two changes will print out something like this:
Test.06.03.2016.12:42

How to import one day old logs

I am new to Python and need some help in being able to import done day old logs. Below is the script I have come up with, but not sure if it is working or if there is a better way to do this.
def fileCreation(path):
now = time.time()
oneday_ago = now - (24*60*60) ## seconds in 1 day
if fileCreation < oneday_ago:
print f
getAuditRecords(f)
I have a script that does import the whole database from mid June 2014 but only need to get day old logs.
Here is a sample of the logs I am trying to import
/mnt/hcp1/R1P/R1P_ora_982_2.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_20_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_29962_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_15593_2.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_9946_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_10746_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_6508_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_17340_2.xml.201409070400
/mnt/hcp1/SCC/SCC_ora_18881_2.xml.201407090400
In order to compare the file creation time to one day ago, you need to actually get the file creation time. Your code is using fileCreation, the function; it doesn't mean anything useful to ask whether that function is less than some time.
Unfortunately, "file creation time" is not a portable concept. If you really want that, you need to write different code for different platforms, which I won't explain.
Usually, you're happy with "file modification time". This is set when the file is created, and updated only when you overwrite or append to the file. You can use getmtime to read this. So:
def fileCreation(path):
now = time.time()
oneday_ago = now - (24*60*60) ## seconds in 1 day
mtime = os.path.getmtime(path)
if mtime < oneday_ago:
print f
getAuditRecords(f)
However, it looks like there's a timestamp attached to each filename. If /mnt/hcp1/R1P/R1P_ora_982_2.xml.201409070400 means that the file was created on 7 September 2014 at 04:00 (and if the timezones, etc. aren't an issue), you may want to consider parsing those strings instead of statting the file.
And once you're parsing date strings, you might as well use the simpler and higher-level datetime library instead of the lower-level time. (You could do this with the previous version too, but since getmtime returns a time-style timestamp, you'd have to convert it manually to use it as a datetime, so there's less advantage.)
So:
def fileCreation(path):
now = datetime.datetime.now()
oneday_ago = now - datetime.timedelta(days=1)
fileext = os.path.splitext(path)[1][1:]
filetime = datetime.datetime.strptime(fileext, '%Y%m%d%H%M')
if filetime < oneday_ago:
print f
getAuditRecords(f)
(Also, I'm not sure what that f is. Maybe you meant path?)
Regarding the "two days ago" part, you should use datetime.datetime and datetime.timedelta
E.g.
import datetime
now = datetime.datetime.now()
two_days = datetime.timedelta(days=2)
two_days_ago = now - two_days

Categories

Resources