Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use DateTime in IronPython

I'm hosting my IronPython in a C# webapp like so:

var engine = Python.CreateEngine();
var scope = engine.CreateScope();
var script = Engine.CreateScriptSourceFromString(pythonCode, SourceCodeKind.Statements);
script.Execute(scope);

And my python code looks like this:

import clr
clr.AddReference('System.Core')

from System import DateTime
theDate = DateTime.Today()

Which generates this error:

IronPython.Runtime.Exceptions.ImportException: Cannot import name DateTime 

I've spent some time on Google and most of the code I found doesn't seem to work anymore.

My IronPython Runtime Version is v2.0.50727 - should I be upgrading? I'd have thought DateTime would've been in from early doors though?

like image 314
littlecharva Avatar asked Sep 24 '09 15:09

littlecharva


People also ask

How do I create a datetime date in Python?

To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.

How do I remove T and Z from timestamp in Python?

To remove timestamp, tzinfo has to be set None when calling replace() function.


1 Answers

Try adding a reference to mscorlib instead of System.Core. We changed the default hosting behavior at some point (2.0.1? 2.0.2?) so that this is done by default when hosting. You can do this from your hosting code with:

engine.Runtime.LoadAssembly(typeof(string).Assembly);
like image 184
Dino Viehland Avatar answered Oct 03 '22 23:10

Dino Viehland