繁体   English   中英

在python中更改日期时间格式

[英]change datetime format in python

我从我的数据库中以这种格式获取这个日期时间。

2016-09-13T08:46:59.953948+00:00

我想将此日期更改为类似的格式

13 sep 2016 08:46:59

我使用过 datetime 模块,例如

import datetime
datetime.datetime.strptime(2016-09-13T08:46:59.953948+00:00, 'changing format')

但它给出了错误

TypeError at /admin/help
must be string, not datetime.datetime

如果您不关心时区和毫秒,您可以尝试以下功能:

from datetime import datetime

def parse_db_time_string(time_string):
    date = datetime.strptime(time_string.split('.')[0], '%Y-%m-%dT%H:%M:%S')
    return datetime.strftime(date, '%d %b %Y %H:%M:%S')

您可以使用 db 字符串调用该函数,然后就像这样:

old_time_string = '2016-09-13T08:46:59.953948+00:00'
new_time_string = parse_db_time_string(old_time_string)

通过导入 Datetime 和 Arrow,您可以将其转换为您需要的格式。 Arrow 是一个用于格式化日期和时间的 Python 库。

import arrow
import datetime

today = arrow.utcnow().to('Asia/Calcutta').format('YYYY-MM-DD HH:mm:ss')
'2016-09-13 15:57:38'

current_date = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S").strftime('%d-%B-%Y %H:%M:%S')
'13-September-2016 15:57:38'

了解更多关于 Arrow https://micropyramid.com/blog/python-arrow-to-show-human-friendly-time/

您可以使用

import datetime
# n is your time as shown in example
your_time = n.strftime("%d/%m/%y %H:%M:%S") 

在尝试制作人类可读的格式时,我推荐django humanize

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM