pythondatetimedatetime-format

How to format datetime like java?


I have the following java code:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SXXX");
String timestamp = simpleDateFormat.format(new Date());
System.out.println(timestamp); 

which prints the date in the following format:

2016-09-20T01:28:03.238+02:00

How do I achieve the same formatting in Python?

What I have so far is very cumbersome:

import datetime
import pytz

def now_fmt():
    oslo = pytz.timezone('Europe/Oslo')
    otime = oslo.localize(datetime.datetime.now())
    msecs = otime.microsecond
    res = otime.strftime('%Y-%m-%dT%H:%M:%S.')
    res += str(msecs)[:3]
    tz = otime.strftime('%z')
    return res + tz[:-2] + ':' + tz[-2:]

Solution

  • ISO 8601

    That format is one of a family of date-time string formats defined by the ISO 8601 standard.

    Python

    Looks like many duplicates of your Question for Python.

    Search Stack Overflow for: Python "ISO 8601". Get 233 hits.

    java.time

    On the Java side, you are working too hard. And you are using troublesome old legacy classes now supplanted by the java.time classes.

    The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to define a formatting pattern. Note that Java 8 has some bugs or limitations with parsing all variations of ISO 8601, remedied in Java 9.

    String input = "2016-09-20T01:28:03.238+02:00" ;
    OffsetDateTime odt = OffsetDateTime.parse ( input ) ;
    

    Ditto, for going the other direction in ISO 8601 format, no need to define a formatting pattern.

    String output = odt.toString () ;  // 2016-09-20T01:28:03.238+02:00
    

    If you really need a java.util.Date for old code not yet updated to the java.time types, you can convert using new methods added to the old classes.

    Fractional second

    Beware of the fractional second.

    When going from Python to Java, this is another reason to avoid the old date-time classes and stick with java.time classes. When going from Java to python, you may want to truncate any nanoseconds value to microseconds as defined by ChronoUnit.MICROS.

    Instant instant = Instant.now().truncatedTo( ChronoUnit.MICROS ) ;
    

    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to java.time.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

    Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.