Posts

Showing posts with the label Iso8601

Converting ISO 8601-compliant String To Java.util.Date

Answer : Unfortunately, the time zone formats available to SimpleDateFormat (Java 6 and earlier) are not ISO 8601 compliant. SimpleDateFormat understands time zone strings like "GMT+01:00" or "+0100", the latter according to RFC # 822. Even if Java 7 added support for time zone descriptors according to ISO 8601, SimpleDateFormat is still not able to properly parse a complete date string, as it has no support for optional parts. Reformatting your input string using regexp is certainly one possibility, but the replacement rules are not as simple as in your question: Some time zones are not full hours off UTC, so the string does not necessarily end with ":00". ISO8601 allows only the number of hours to be included in the time zone, so "+01" is equivalent to "+01:00" ISO8601 allows the usage of "Z" to indicate UTC instead of "+00:00". The easier solution is possibly to use the data type converter in JAXB, since JAXB m...

Convert A Datetime.timedelta Into ISO 8601 Duration In Python?

Answer : Although the datetime module contains an implementation for a ISO 8601 notation for datetime or date objects, it does not currently (Python 3.7) support the same for timedelta objects. However, the isodate module (pypi link) has functionality to generate a duration string in ISO 8601 notation: In [15]: import isodate, datetime In [16]: print(isodate.duration_isoformat(datetime.datetime.now() - datetime.datetime(1985, 8, 13, 15))) P12148DT4H20M39.47017S which means 12148 days, 4 hours, 20 minutes, 39.47017 seconds. This is a function from Tin Can Python project (Apache License 2.0) that can do the conversion: def iso8601(value): # split seconds to larger units seconds = value.total_seconds() minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) days, hours, minutes = map(int, (days, hours, minutes)) seconds = round(seconds, 6) ## build date date = '' if days: d...