Timezone aware datetime to string? [duplicate]

荒凉一梦 提交于 2021-01-07 12:54:17

问题


I am retrieving a timezone aware DateTime object from my postgres db.

Now I want to convert this datetime object into it's string representation.

Normally I would do something like this:

str(datetime.datetime(2016, 1, 15, 9, 59, 45, 165904))
'2016-01-15 09:59:45.165904'

But here I have:

datetime.datetime(2016, 1, 15, 9, 59, 45, 165904, tzinfo=<UTC>)

I cannot find a way anywhere to find the str repesentation of the given object.


回答1:


Here is a simple example of how to convert a datetime object to a string:

import datetime
import pytz

x = datetime.datetime(2016, 1, 15, 9, 59, 45, 165904, tzinfo=pytz.UTC)
print(datetime.datetime.strftime(x, "%d/%m/%Y"))

Output

15/01/2016

Options for the format string to pass into the strftime() function are in the Python documentation.



来源:https://stackoverflow.com/questions/34808721/timezone-aware-datetime-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!