6

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:]
thebjorn
  • 26,297
  • 11
  • 96
  • 138
  • Use `otime.isoformat()`? – Phylogenesis Sep 20 '16 at 12:20
  • `otime.isoformat()` gives me 6 digits for microseconds. – thebjorn Sep 20 '16 at 12:21
  • 1
    If that is actually important, then I suspect you will have to use string slicing to reduce it to milliseconds. But anything that is reading such a standardised timestamp should be perfectly happy with any number of digits after the decimal point (that's the point of the standard). – Phylogenesis Sep 20 '16 at 12:25
  • I'm not a java programmer, but it seems that parsing iso-formatted datetimes is non-trivial in java..(?) – thebjorn Sep 20 '16 at 12:48
  • If I change the java format string to `SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")` the string created can be parsed by the same format object. It still doesn't handle 6-digit fractional seconds though.. – thebjorn Sep 20 '16 at 13:14

2 Answers2

3

This worked for me in 2021 using Python 3. The output was '2022-03-14T04:20:30.069308'

import datetime
datetime.datetime.now().isoformat()

Getting timezone info for the version of python I had, seemed to require a different lib. Output was: '2022-03-18 18:43:29.976051-07:00'

import dateutil.tz
str(dateutil.tz.datetime.datetime.now(dateutil.tz.gettz()))

Later, in 2022 on a different computer with a newer python version, but lacking dateutil (I had not ran pip install python-dateutil) I found this works:

>>> import datetime
>>> datetime.datetime.now().astimezone().isoformat()
'2022-04-20T15:20:05.196508-07:00'
>>> datetime.datetime.now(datetime.timezone.utc).isoformat()
'2022-04-20T22:20:10.064409+00:00'
MarkHu
  • 1,694
  • 16
  • 29
1

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.

  • The java.time classes handle values with up to nanosecond resolution, nine digits of decimal fraction.
  • The Python datetime type seems to have a microseconds resolution, for six decimal places.
  • The old legacy date-time classes in Java are limited to millisecond resolution, for three digits of decimal fraction.
  • The ISO 8601 standard prescribes no limit to the fraction, any number of decimal fraction digits.

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 2
    The Java discussion is great and all, but the question seems to be just asking how to do it in Python – OneCricketeer Sep 20 '16 at 19:27
  • No, the Java discussion is on point (I've used Python for almost two decades, not so with Java). This is an integration project with another group so it is always helpful with background and up-to-date info. – thebjorn Sep 20 '16 at 19:44