1

Is there an easy/efficient way of converting the 'Current Solr date' to the 'Desired output' shown below ? I thought of using regex or string methods to clean up the Solr dates but if there is a method to use in Python that converts these dates from Solr it would be great.

Current Solr date:

'2020-01-21T12:23:54.625Z'

Desired output (in datetime module format):


'2020-01-21 12:23:54' 
blah
  • 674
  • 3
  • 17
  • 1
    since you don't want any UTC offset specification in your output, you could just strip the `Z`, parse [to datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat) and call [`datetime.isoformat(' ')`](https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat) I guess – FObersteiner Feb 22 '21 at 17:25
  • Do you maybe know how to transform the desired output back to the solr format ? (Was part of my "viceversa" question). Thanks :) – blah Mar 10 '21 at 10:54
  • 1
    in your example, you ignore the milliseconds - is that correct? – FObersteiner Mar 10 '21 at 11:16
  • the miliseconds can be ignored, yes (unless solr makes an issue out of this) – blah Mar 10 '21 at 12:05
  • 1
    ok, I've used a `.replace(microsecond=0)` in my answer; you can always remove that to keep them in. but note that Python will display *microseconds* (6 digits). stripping those to *milliseconds* is another detour ;-) – FObersteiner Mar 10 '21 at 12:25

1 Answers1

2

Here's a quick round-trip from string to datetime object to string again, including a couple of options. Hope this gets you going.

string → datetime (microseconds kept)

from datetime import datetime

s = '2020-01-21T12:23:54.625Z'

# to datetime object, including the Z (UTC):
dt_aware = datetime.fromisoformat(s.replace('Z', '+00:00'))
print(repr(dt_aware))
# datetime.datetime(2020, 1, 21, 12, 23, 54, 625000, tzinfo=datetime.timezone.utc)

# to datetime object, ignoring Z:
dt_naive = datetime.fromisoformat(s.strip('Z'))
print(repr(dt_naive))
# datetime.datetime(2020, 1, 21, 12, 23, 54, 625000)

datetime → string (microseconds stripped)

# to isoformat string, space sep, no UTC offset, no microseconds
print(dt_aware.replace(microsecond=0, tzinfo=None).isoformat(' '))
# 2020-01-21 12:23:54
print(dt_naive.replace(microsecond=0).isoformat(' '))
# 2020-01-21 12:23:54

# ...or with a Z to specify UTC and a T as date/time separator
print(dt_aware.replace(microsecond=0).isoformat().replace('+00:00', 'Z'))
# 2020-01-21T12:23:54Z

# to isoformat string, with Z for UTC, naive / no tzinfo:
print(dt_naive.replace(microsecond=0).isoformat() + 'Z') # just add Z as a suffix
# 2020-01-21T12:23:54Z

You might also want to have a look at the timespec kwarg of datetime.isoformat if you need a specific precision, e.g. milliseconds.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72