In python, by importing datetime module and using various functions of class datetime.datetime we could get basic dates with formatting and even date arithmetic for deployment.
For example, datetime.datetime.now() will return today's date.
But, today when I run this program there was no internet connection in my computer but still it outputs today's date.
So, how datetime.datetime.now() could return proper date? Is the algorithm automatically increments after 24 hours time ?
tl;dr datetime.datetime.now() uses the clock built into your computer.
Computers have been able to keep fairly accurate time for much longer than the Internet has existed.
For example, PCs feature what's called a real-time clock (RTC). It is battery-powered and can keep the time even when the computer is switched off.
Interestingly, some distributed algorithms require very accurate clocks in order to operate reliably. The required accuracy far exceeds anything that a simple oscillator-based clock can provide.
As a result, companies like Google operate GPS and atomic clocks in their data centres (and even those are not without potential issues, as was demonstrated, for example, on 26 January 2017, when some GPS clocks were out by 13 microseconds for ten hours).
Even though the data centres are connected to the Internet, neither GPS nor atomic clocks require an Internet connection to operate. Besides, someone needs to keep all that Internet time infrastructure running... it can't be that everyone gets their time "off the Internet". ;)
Now that we're on the subject of distributing the time across computer networks, the main protocols for doing that are NTP (Network Time Protocol) and PTP (Precision Time Protocol).
The documentation for datetime.datetime.now() does not state the time is received from the internet.
Return the current local date and time. If optional argument tz is
None or not specified, this is like today(), but, if possible,
supplies more precision than can be gotten from going through a
time.time() timestamp (for example, this may be possible on platforms
supplying the C gettimeofday() function).
If tz is not None, it must be an instance of a tzinfo subclass, and
the current date and time are converted to tz’s time zone. In this
case the result is equivalent to
tz.fromutc(datetime.utcnow().replace(tzinfo=tz)). See also today(),
utcnow().
The datetime is received from the computer time, if you are running windows for example, try to change time from the window and the python will print the time that you changed.
check its documentation : https://docs.python.org/2/library/datetime.html
Related
Suppose, it's originally 18:00 (06:00 PM) right now. But the time of my PC is 17:29 (05:29 PM).
Now my code works like:
>>> from datetime import datetime
>>> str(datetime.now())
'2021-10-20 17:29:28.653283'
How can I get a datetime object that will return the original datetime i.e. 18:00 (06:00 PM).
Something like:
'2021-10-20 18:00:00.653283'
Important: Whatever the PC time is I need to get the original time. So changing the PC time is not an option.
X/Y problem - maybe your pc needs the time synchronized? Check the calendar settings and ensure synchronization servers are working. Try synchronizing manually.
It could be weak CMOS battery or oscillator/timer issue with the motherboard, if your pc time drifts away over time.
Also note that wrong time will make some browser connections fail (I do not know how big time difference causes it).
Is your program communicating with anything outside the machine? If not, why do you need exact objective time?
If you do communicate with anything over web - you can query the well known time servers like nist.gov, but remember to account for delays and so on, you also have to store the offset to reuse it in future or query servers every time.
If your program does not need to communicate, consider whether absolute objective time is really needed. In isolated system, you can't really tell, nor you usually need to.
I am having an issue figuring out how to write a publisher node (ROS Python) that will send the subscriber the actual time (IE: 12:46) which I need to do for my homework. I need to publish the actual time, so that the subscriber can use that time, and a difference in time requested through a service to calculate the time somewhere else in the world. (Ie: Node1 publishes time in New York, Node2 subscribes and requests the time difference between current location-New York- and London. Node1 sends the information on the time difference to Node2. Node2 takes current time and time difference and adds them to find out the current time in London)
I have googled the issue and I cannot find any helpful information. I have found some confusing sources that say how to get the simulated time in seconds, and (maybe) the clock time in seconds, but I did not really understand what they were saying enough to use the information.
code that I have so far: Sorry, IDK how to format it right on this website
#!/usr/bin/env python
from beginner_tutorials.srv import TimeDiff, TimeDifResponse
from std_msgs.msg import Time
import rospy
pub = rospy.Publisher('currentTime', Time, queue_size=10)
CurrentTime= localtime()
def setupPublisher():
rospy.init_node('talker', anonymous=True)
rate = rospy.Rate(5) # 5hz
while not rospy.is_shutdown():
global CurrentTime
CurrentTime= localtime()
pub.publish(CurrentTime)
rate.sleep()
if __ name __ == "__ main __":
setupPublisher()
I don't really have any code to share because I don't know how to incorporate the time. This is what I have so far, but I don't think it's right
It should publish the time to the subscriber, but I have no idea what it is doing, or what variables I should be using, or anything for that matter. We didn't learn about this in class at all.
You should be familiar with all the ROS pre-defined message types (although some are significantly more used than others), including the std_msgs std_msgs/Header message. It includes the std_msgs/Time message and a frame_id (String) term, for which you could store the location of the time.
Also, the ROS time type (for which there is a std_msg Time wrapping it), needs to be acquired from the appropriate ROS (rospy) method, not localtime() (although you could make the time from the localtime() if you wanted).
For more time/Time references, here is the overview, client time libraries, and python / rospy specifics. The gist is the three (completely equivalent) functions:
rospy.Time.now() #get time as rospy.Time instance
rospy.get_rostime() #get time as rospy.Time instance, same as .now()
rospy.get_time() #get time as float secs
Remember the standard for the "current time" is seconds from 1970 UTC/GMT (timezone +-0). rospy.Time holds to this as it uses python's time.time() for the current ROS time (which is just a tuple of the seconds since and extra nanoseconds from the second). This will allow you to use the rest of the python tools to format it as you wish. ROS also allows a "simulated time" with the Clock, as you saw, but that is a fun feature for simulation that isn't what you get by default when you use Time (no need to worry).
I'm novice to programming and learning python3.
Recently I'm trying to make cryptocurrency trading system using binance's api.
Here's the api document.
The logic and explanation about timestamp in the document is as follows :
Timestamp, to be sent which should be the millisecond timestamp of when the request was created and sent.
if (timestamp < serverTime && (serverTime - timestamp) <= recvWindow)
{ // process request } else { // reject request }
According to this logic, the time I sent the request should be less than the time on the server. The problem is that I have not passed this logic.
When I call time.time() and server time using this code,
import requests
import simplejson as json
import time
base_url = "https://api.binance.com"
servertime_endpoint="/api/v1/time"
url = base_url + servertime_endpoint
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
print(int(t)-result["serverTime"])
time.time() is bigger than server time so that I get return from last sentence with positive value. What should I do?
This is most likely due to the operating system you are running using a clock with a lower resolution than the one the server is running. When running on a Linux or Mac OS, Python uses a system call for time.time() that returns time down to microsecond resolution (or better). When running on a Windows machine, it only returns time down to millisecond resolution.
You can check the resolution of the time.time() function by programming a busy loop and waiting until the time changes: use the code in this incredibly useful answer to see what your resolution is.
If you are running on an OS with a resolution of ~0.001 second (1 millisecond) while the server is reporting times at a resolution of ~0.000001 second (1 microsecond), then even if your clocks were exactly in sync and there is zero network latency, you would still expect your time to be ahead of the server time on 50% of the calls simply due to quantization noise. For instance, if the server reports a time of 12345.678501 (microsecond resolution), your machine would report a time of 12345.679 (millisecond resolution) and appear to be 499 microseconds ahead.
Some quick solutions are to:
check if the server time rounds to your machine time and call that acceptable even if it appears your time is ahead of the server time;
subtract 500 microseconds to your time to guarantee that quantization noise can't put you ahead of the server;
increase the timing threshold by 500 microseconds and check that the absolute value of the difference between your time and the server time are within the bounds;
run your code on a operating system with a higher resolution system clock.
I'm writing a Python script, and I need to use the Python schedule module.
I want to execute a job every day at midnight, so I wrote something like
schedule.every().day.at("00:00")
Problem is that I want to run at my midnight, because I'm uploading this script to a server and I don't know its location and hence its timezone.
How could I achieve my goal?
from time import gmtime, strftime
print strftime("%z", gmtime())
Pacific Standard Time
import time
time.tzname
it returns a tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone.
Schedule doesn't support timezones, a pull-request that included the initial changes to support that was rejected (the source for that can be found here.
So either look at those changes, or run something at 00:00 that emails you a message, so you can deduct how much the offset from that server is to yours.
If you do so check on a regular basis especially late October/March, so you can determine if the server is subject to daylight saving changes for its localtime, and adjust accordingly.
I have a UTC time (epoch Unix time) formatted as timestamp as below.
1496224620
(Human readable value: May 31, 2017 09:57:00)
I need to convert the timestamp formatted as Unix time into GPS time format as below.
1180259838
(Human readable value: May 31, 2017 09:57:00)
I need a python program (algorithm is fine for me) to convert timestamp formatted as Unix time to timestamp formatted as GPS time.
There is one PHP program to do so. I can change from PHP code to Python code to have a Python program by myself. But I think there is also a short way (built-in function of Python) that can implement my expectation more effective.
Here is the link of PHP program
https://www.andrews.edu/~tzs/timeconv/timealgorithm.html
Just subtract 315964782 from the UNIX time.
GPS Time starts on January 5, 1980. UNIX time starts on January 1, 1970. They simply have different starting points, or Epochs. The difference between those two Epochs is the number of seconds between those two dates PLUS 18 GPS leap seconds (so far).
As others have noted, GPS leap seconds are periodically added as the Earth's rotation gradually slows.
we must update our source code manually for each time the leap second occurs (ex. next 2018, 2019,...)? Is there any feasible way to prevent this problem?
Many devices have a message that indicates the "current" number of GPS seconds in effect. My C++ NeoGPS library has an example program that requests the current number of GPS seconds from a ublox device (binary message defined here). See ublox NEO-xx specifications for more information regarding the NAV-TIMEGPS message.
Other manufacturers may have their own protocols and messages for obtaining the current GPS leap seconds.
HOWEVER:
Most GPS devices report times in UTC, with the leap seconds already included. Unless you are using a GPS time based on the start of the week (midnight Sunday), you should not need to know the GPS leap seconds.
If you are trying to convert from a "GPS time since start of week", then you would also need to know the current GPS week number to convert "GPS time of week" to UTC.
ublox devices report some fix information with a timestamp that is "GPS milliseconds since start of week." This NeoGPS file shows several methods for converting between "GPS milliseconds since start of week" and UTC.
How about:
import datetime
datetime.datetime.fromtimestamp(int("1284101485")).strftime('%B-%Y-%d %H:%M:%S')