I'm trying to print milliseconds from date in python, I used below code to get millisecond since I'm new to Python I would like to check with someone here if this is that right way of getting milliseconds:
import datetime
def findmili(date):
return int(date.strftime("%s")) * 1000
x = datetime.datetime.strptime('01/27/2017', "%m/%d/%Y")
print findmili(x)
Can someone please help me to validate this, if this is not right way of getting can you tell what's the exact way of getting this in python.
Looks like something wrong, I'm trying to get millisecond of Jan 12 2017 but my program returns this value: 1484179200000. If I convert those milliseconds to a date using this online utility, it shows Jan 11 2017 instead of Jan 12 2017.
Note: I have to use Python 2.7 version only. :(
First of all, I believe a bit of clarification in your question would be to indicate that you are looking for milliseconds that have elapsed from epoch till the date you provide as that is what the tool seems to be doing.
A simple way to do something like that is like this :
int(datetime.datetime.now().strftime("%s")) * 1000
replace datetime.datetime.now() with your own datetime object. So the completed function might be something like this :
import datetime
def findmili(date):
return int(date.strftime("%s")) * 1000
x = datetime.datetime.strptime('10Nov2017', '%d%b%Y')
print findmili(x)
As an aside, your code won't actually run in python2.7. This is because, you have made an error in line 6 where instead of d = datetime.strptime(myDate, "%m/%d/%Y"), it should actually be d = datetime.datetime.strptime(myDate, "%m/%d/%Y")
Another aside, your code is also correct ( except from the error above ) . Its returning 1484150400000 which returns as Thu Jan 12 2017 00:00:00 GMT+0800.
When you use that online site notice that its result depends on where the site believes that you are situated. In the time zone where I live (Eastern Canada) I get the correct result. However, if I change the timezone on the site to the one for Phoenix, Arizona in the United States, for instance, this is the result.
I suspect that this is why you are getting an unexpected result.
Related
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.
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.
I'm really new to programming and I only just started using Python, if anyone could edit the code I put up to make it work how I want it to then please do.
I was wondering if I could make the date show up, on my python program but make it different for different regions, so if someone opened the program in United Kingdom the day would show up first and if it was in the US it would show the month or year first etc.
This is what I have so far.
import datetime
currentDate = datetime.date.today()
print(currentDate.strftime('Todays date is: %d %B %Y'))
I currently have it set so it shows the day first then the month then the year.
Is there anyway to make it use it in a different order depending on what country you're in?
Does this work for you?
>>> import datetime
>>> today = datetime.date.today()
>>> print(today.strftime('%x'))
09/10/15
Specifically, you probably should look at the %c, %x, and %X format codes. See 8.1.8. strftime() and strptime() Behavior for more information on how to use the strftime method.
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
currently, I have the following current timestamp value example in seconds.
1299196800. It means
4 March 2011 0:0:0 in Greenwich (GMT)
4 March 2011 8:0:0 in Malaysia (GMT
+8)
Currently, if my Python script pass in 1299196800 to a flot graphing javascript library, it will always show Greenwich's time 4 March 2011 0:0:0 instead of Malaysia's time 4 March 2011 8:0:0, although the client machine is using Malaysia timezone.
My python server will always having same time zone as client machine. We want 4 March 2011 8:0:0 to be shown in client side.
Hence, for workaround purpose on the limitation of flot graphing library, instead of passing 1299196800, I would like to pass in
# 8 is timezone offset.
# 1299196800 is current timestamp.
pseudo_timestamp = 1299196800 + 8 * 60 * 60
May I know how can I generate the above "pseudo timestamp" in python? Is manipulate with a constant timezone a good idea? Will it encounter any problem when comes to day light saving?
The UTC time in flot is by design: look for timestamp here, and fixing the time offset is the recommended solution.
Consider that the flot timestamp are expressed in milliseconds, so you'll have to multiply your example offset by 1000.
It is not a good idea, though, to use a constant timestamp: in general you'd try to discover the client offset, but since you are sure that it's the same of the server, you can use the server data to do that.
Use time.daytime to discover if a daylight saving is active, and then use time.timezome or time.altzone accordingly to get the offset in hours.
Python doc on time is here
Given that, you can adjust your timestamps converting the offset in milliseconds and adding it to you timestamps (which you already did :) )
You use datatime object with tzinfo which is time-zone aware.
Here is a short-snippet of how you actually do it.
import datetime
from datetime import tzinfo, timedelta
class GMT8(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=8)
def tzname(self, dt):
return "GMT +8"
def dst(self,dt):
return timedelta(0)
malaysiatime = GMT8()
o = datetime.datetime.fromtimestamp(1299196800,malaysiatime)
print o
# prints 2011-03-04 08:00:00+08:00