1

Is it a way to replace/customize the default __str__ of datetime?

from datetime import datetime
x = datetime.now() # x can be any date from parameters
print(x) # str(x) returns 2020-10-07 10:38:08.048291 too, but I want a different format

I need to change the default __str__ behave for other functions like json.dump(x, default=str).

x = 12, 'abc', datetime.now(), 223, ....
json.dump(x, default=str)
ca9163d9
  • 27,283
  • 64
  • 210
  • 413
  • See https://docs.python.org/3/library/datetime.html#datetime.date.strftime – mousetail Oct 07 '20 at 14:43
  • Any reason not to use [strftime](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)? –  Oct 07 '20 at 14:43
  • I've updated the question. The purpose is for the call of `json.dump(x, default=str)` – ca9163d9 Oct 07 '20 at 14:47
  • Doesn't change the fact that you can use `strftime`... `json.dump((12, 'abc', datetime.now().strftime("your/format")))` – Tomerikoo Oct 07 '20 at 15:29
  • @ca9163d9 I think I found a good un-intrusive [solution](https://stackoverflow.com/a/64247039/941531) for json conversion case instead of modifying `datetime` `__str__` method. – Arty Oct 07 '20 at 15:32

2 Answers2

1

I think next is a cleaner un-intrusive approach for your case rather than modifying datetime class's __str__ method. You provide custom convertors for any types you need like datetime, while the rest is tried to be converted to json if not possible then falling back to using str(x) if it is json-unconvertable type (like numpy array in my example).

Try it online!

import json
from datetime import datetime
import numpy as np

obj = {
    'time': datetime.now(),
    'other': [1,2,3],
    'str_conv': np.array([[4,5],[6,7]]),
}

def json_default(x):
    if isinstance(x, datetime):
        return x.strftime('%H:%M:%S')
    else:
        try:
            json.dumps(x)
            return x
        except:
            return str(x)

print(json.dumps(obj, default = json_default))

output

{"time": "18:24:57", "other": [1, 2, 3], "str_conv": "[[4 5]\n [6 7]]"}
Arty
  • 14,883
  • 6
  • 36
  • 69
0

You can change the output format using strftime(). It's described here under "Formatting and parsing".

DDD1
  • 361
  • 1
  • 11