Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 890
Michael Avatar asked Apr 22 '15 20:04

Michael


1 Answers

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)
like image 89
Jeff Hardy Avatar answered Sep 28 '22 04:09

Jeff Hardy