How to convert from IronPython date and time to .NET DateTime?

Literally the opposite of this question , is there an easy way to get .Net DateTimefrom IronPython DateTime?

It's clear that

  • Print a string and parse it or
  • Flush all parts of the date to the constructor DateTime

but they are both messy. This also does not work:

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

Is there an easy way or short way to get Tickswhat .Net wants?

+4
source share
3 answers

, 2.7.6 , clr.Convert , . , 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) .

+2

, , . 31f5c88, ( ) 2.7.6.

timetuple :

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

# For UTC times, you need to pass 'kind' as a kwarg
# because of Python rules around using * unpacking
udt = datetime.now() 
ud = DateTime(*udt.timetuple()[:6], kind=DateTimeKind.Utc)
+5

DateTime . , - :

def cs_date(date):
    return DateTime(*date.timetuple()[:6] + (date.microsecond/1000,))
+1

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


All Articles