carl
carl

Reputation: 4436

convert datetime object to string Python

I need to create strings of the form yyyyMMdd'T'HHmmss.SSSZ to store a Python datetime object in elasticsearch (basic_date_time). This seems to be a standard time string, but I have trouble to make elasticsearch accept the date? I think I am getting my datetime -> string conversion wrong? I am using

datetime_object.strftime("%Y%m%d'T'%H%M%S")

Does anybody know what is going wrong here? Also is there a way to create std. datetime strings rather than using .strftime()?

thanks carl

Upvotes: 1

Views: 2526

Answers (1)

Matteo T.
Matteo T.

Reputation: 1417

You can do the following to get the basic_date_time of Elasticsearch with 3 digits of milliseconds:

d = datetime_object.astimezone()
d.strftime("%Y%m%dT%H%M%S.%f")[:19] + d.strftime("%z")

Which gives "20180124T103350.376+0100 for datetime_object = datetime.now()

Upvotes: 3

Related Questions