13

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

This is not the equivalent of Get timer ticks in Python, which asks 'how do I get the number of ticks since midnight?'.

I am asking how do I get the number of ticks of a given datetime. By ticks I mean system.datetime.ticks:

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

By 'get equivalent of' I mean 'what is the python code that will give the equivalent output of the C# code?'.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
eggbert
  • 3,105
  • 5
  • 30
  • 39

1 Answers1

20

According to the referenced page, DateTime.Ticks returns the number of ticks since 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 of a timedelta. Then, given a datetime object, the delta is calculated 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 favourably to that returned by C# using DateTime.UtcNow.Ticks.

Notes:

  • UTC times are assumed.
  • The resolution of the datetime object is given by datetime.resolution, which is datetime.timedelta(0, 0, 1) or microsecond resolution (1e-06 seconds). C# Ticks are purported to be 1e-07 seconds.
mhawke
  • 84,695
  • 9
  • 117
  • 138