6

Literally the inverse of this question, is there an easy way to get a .Net DateTime from an IronPython datetime?

Clearly, one could

  • Output a string and parse it or
  • Dump all the date parts into a DateTime constructor

but those are both messy. This doesn't work either:

pydate = datetime.datetime.now()
csharp = DateTime(pydate) # Crashes, because .Net wants a 'long' for Ticks

Is there an easy cast or a short way to get the Ticks that .Net wants?

Community
  • 1
  • 1
Michael
  • 8,362
  • 6
  • 61
  • 88

3 Answers3

5

I was fairly certain a direct conversion was already allowed, but I was wrong. I added it in 31f5c88 but that won't be available until (currently unscheduled) 2.7.6.

In the meantime the best way would be to use the timetuple method to get the parts:

dt = datetime.now()
d = DateTime(*dt.timetuple()[:6])

# For UTC times, you need to pass 'kind' as a kwarg
# because of Python's rules around using * unpacking
udt = datetime.now() 
ud = DateTime(*udt.timetuple()[:6], kind=DateTimeKind.Utc)
Michael
  • 8,362
  • 6
  • 61
  • 88
Jeff Hardy
  • 7,632
  • 24
  • 24
3

Now that 2.7.6 has been released, you can use clr.Convert to make an explicit cast, if needed. There could be better ways to do this, but I'm stealing this one from Jeff Hardy's commit.

>>> from System import DateTime
>>> from datetime import datetime
>>> from clr import Convert
>>> now_py = datetime.now()
>>> now_py
datetime.datetime(2020, 1, 1, 18, 28, 34, 598000)
>>> Convert(now_py, DateTime)
<System.DateTime object at 0x00000000006C [1/1/2020 6:28:34 PM]>
>>> now_py == Convert(now_py, DateTime)
True

DateTime(pydate) still crashes.

Michael
  • 8,362
  • 6
  • 61
  • 88
1

Jeff's answer gets a DateTime to the second. If you want to stretch the precision to the millisecond, you can use something like this:

def cs_date(date):
    return DateTime(*date.timetuple()[:6] + (date.microsecond/1000,))
Community
  • 1
  • 1
Michael
  • 8,362
  • 6
  • 61
  • 88