How do I convert the following python code to Java?
import time
str(int(time.time() * 1e6))
I have tried the following snippet in my Java project.
private static String runPython(String script) throws Exception{
File file = new File("test.py");
if(file.exists()) {
file.delete();
}
BufferedWriter out = new BufferedWriter(new FileWriter("test.py"));
out.write(script);
out.close();
Process p = Runtime.getRuntime().exec("python test.py ");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
return ret+"";
}
private static String getFromPython() {
try {
String prg = "import time\nprint str(int(time.time() * 1e6))\n";
return runPython(prg)+"";
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static String getFromJava() {
String result = ((System.currentTimeMillis() / 1000) * 1e6)+"";
return result;
}
public static void main(String[] args) {
System.out.println("Python Version: "+getFromPython());
System.out.println("Java Version: "+getFromJava());
}
This are the different results am getting
run:
Python Version: 1417515400105953
Java Version: 1.4175154E15
Any one with a better approach? How is the time.time() in python different from System.currentTimeInMillies() in Java?
The two values you're getting are very similar - it's just that the representations are different. That's primarily because in the Java version you're multiplying by 1e6
which is a floating-point literal, so the result is a double
, which is being represented in scientific notation due to its size. Python is a bit freer with its numeric types, and is choosing to display the result without using scientific notation.
If instead you multiply by the integer literal 1000000 you'd get something like "1417515400000000"
- which looks closer to the Python version, but is truncated to the second.
If instead of dividing by 1,000 and then multiplying by 1,000,000 you just multiplied by 1,000, you'd get something more like "1417515400105000"
. That's still truncated to the millisecond, but I suspect that your clock isn't likely to be more accurate than that anyway.
As an aside, I'd recommend using String.valueOf(x)
to convert non-string types to strings rather than using x + ""
- it better describes what you're trying to do, as you're really not trying to perform a concatenation at all. So I'd suggest that your getValueFromJava
method should be:
public static String getFromJava() {
return String.valueOf(System.currentTimeMillis() * 1000);
}
(It's unclear why you need this as a string in the first place, but that's a different matter.)
See more on this question at Stackoverflow