Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ISO datetime contains 'T' character

How can I make this lambda get a timestamp that doesn't include the T in the timestamp?

@app.route("/bookings", methods=['GET'])
def bookings():
    bookings = Booking.query.all()
    dictList = []
    for b in bookings:
        dictList.append(b.as_dict())
    dthandler = lambda obj: (
                    obj.isoformat()
                    if isinstance(obj, datetime.datetime)
                    or isinstance(obj, datetime.date)
                    else None)
    return json.dumps(dictList, default=dthandler)

eg timestamp:

2015-04-11T01:30:00
like image 680
el_pup_le Avatar asked Mar 16 '23 11:03

el_pup_le


1 Answers

The datetime.isoformat() function takes an argument: the separator to use. It defaults to 'T' if omitted; if you want something else, then pass in that instead:

obj.isoformat(' ')

Quoting the documentation:

The optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result.

You can also convert the object to a string here; datetime.__str__() is basically the same thing as datetime.isoformat(' ').

Demo:

>>> from datetime import datetime
>>> obj = datetime(2015, 4, 21, 20, 0, 0)
>>> obj.isoformat()
'2015-04-21T20:00:00'
>>> obj.isoformat(' ')
'2015-04-21 20:00:00'

Only the datetime.isoformat() method takes that argument; date.isoformat() does not; you'll have to adjust your default handler to differentiate between date and datetime objects for this to work, or just use str() on either:

dthandler = lambda obj: (
                obj.isoformat(' ') if isinstance(obj, datetime.datetime)
                else obj.isoformat() if isinstance(obj, datetime.date)
                else None)

or

dthandler = lambda obj: (
                str(obj) if isinstance(obj, (datetime.datetime, datetime.date))
                else None)
like image 142
Martijn Pieters Avatar answered Mar 19 '23 22:03

Martijn Pieters