Member-only story

How to convert DateTime objects to Python-friendly ISO8601 strings in C#

(and deserializing them in C# as well)

Photo by SHAHBAZ ZAMAN

A while ago my team needed a way to convert C# DateTime objects into strings that Python’s datetime module could parse. Everything else was in ISO8601 format, so for consistency’s sake this needed to be as well.

Our use case was very simple: serialize a DateTime object to an ISO8601-format string, then read it in our Python application. A short hunt through documentation and forums later, and we had our format string:

@”yyyy-MM-ddTHH:mm:ss.ffffff+00:00"

This has been working nicely until now, but today I settled in to write some C# code that requires both serializing and deserializing these strings and I ran into a surprising amount of trouble! After overcoming a few painful gotchas, I feel it’s worth sharing my learnings with the rest of the class:

  1. To convert from a DateTime object to a Python-friendly ISO8601 string, use
    dateTime.ToString(@”yyyy-MM-ddTHH:mm:ss.ffffff+00:00");
  2. To convert from a Python-friendly ISO8601 string to a DateTime object, use
    DateTime.ParseExact(str, @”yyyy-MM-ddTHH:mm:ss.ffffff+00:00", null)
  3. When a custom format string is used to parse a string into a DateTime object, the DateTime…

--

--

Adam Fisher / fisher king (@therightstuff)
Adam Fisher / fisher king (@therightstuff)

Written by Adam Fisher / fisher king (@therightstuff)

Software developer and writer of words, currently producing a graphic novel adaptation of Shakespeare's Sonnets! See http://therightstuff.bio.link for details.

No responses yet