How do I convert from an IronPython datetime to a .NET DateTime?
Asked Answered
P

3

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?

Precautious answered 22/4, 2015 at 20:44 Comment(0)
P
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.

Precautious answered 13/10, 2016 at 18:58 Comment(0)
C
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)
Callis answered 26/4, 2015 at 7:59 Comment(0)
P
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.

Precautious answered 13/10, 2016 at 18:58 Comment(0)
P
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,))
Precautious answered 5/8, 2016 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.