18

I'm calling an IronPython script and passing it a .NET object that contains a DateTime structure.

I'm trying to use IronPython's JSON support to serialize the object as JSON.

Everything works great until I encounter the .NET DateTime.

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

casperOne
  • 73,706
  • 19
  • 184
  • 253
ScArcher2
  • 85,501
  • 44
  • 121
  • 160
  • Does the very last comment help? http://msdn.microsoft.com/en-us/library/system.datetime%28v=vs.90%29.aspx – keyboardP Jun 09 '11 at 17:30
  • 1
    It was slightly helpful. I can manually pull the fields out of the DateTime and construct a new datetime, but I was hoping for an easy way. It seems like this would be somewhat common. – ScArcher2 Jun 09 '11 at 17:47

2 Answers2

19

Anticipating that people might like to convert between these we actually make it really easy:

import datetime
from System import DateTime
datetime.datetime(DateTime.Now)
Dino Viehland
  • 6,478
  • 20
  • 25
5

As we know, the datetime type has the following structure: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]). So all you need is to find a way how to fulfill the required options.

strptime is not yet implemented (otherwise you'd have the ability to simply call datetime.datetime.strptime(DateTime.Now.ToString(format), format).strftime(format)) in IronPython. Instead, you can use the following code (not very optimized one) for now:

from System import DateTime

import datetime

d = DateTime.Now

print datetime.date(d.Year, d.Month, d.Day)
print datetime.datetime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second)
Michael
  • 8,362
  • 6
  • 61
  • 88
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52