What is the python equivalent of C # system.datetime.Ticks ()?

I would like to get the python equivalent of timestamp.Ticks (), however I need it to come from a python datetime, not a time object.

This is not equivalent to Get timer ticks in Python , which asks, "How do I get the number of ticks from midnight?"

I ask how to get the number of ticks of a given time. By ticks, I mean system.datetime.ticks:

https://msdn.microsoft.com/en-us/library/system.datetime.ticks%28v=vs.110%29.aspx

By "get the equivalent" I mean "what is Python code that will give equivalent C # code output?".

+5
source share
1 answer

According to the reference page, DateTime.Ticks returns the number of ticks from 0001:01:01 00:00:00 . There are 10 million ticks per second.

In Python, datetime(1, 1, 1) represents 0001-01-01 00:00:00 . You can calculate the number of seconds using the total_seconds() method for timedelta . Then, given the datetime object, the delta is computed and converted to ticks, like this:

 from datetime import datetime t0 = datetime(1, 1, 1) now = datetime.utcnow() seconds = (now - t0).total_seconds() ticks = seconds * 10**7 

As a function, this is:

 def ticks(dt): return (dt - datetime(1, 1, 1)).total_seconds() * 10000000 >>> t = ticks(datetime.utcnow()) >>> t 6.356340009927151e+17 >>> long(t) 635634000992715136L 

This value compares favorably with the returned C # using DateTime.UtcNow.Ticks .

Notes:

  • Estimated UTC time.
  • The resolution of a datetime object is given by the formula datetime.resolution , which is datetime.timedelta(0, 0, 1) or microsecond resolution (1e-06 seconds). C # Ticks count 1e-07 seconds.
+8
source

Source: https://habr.com/ru/post/1216524/


All Articles