django中的日期格式

时间:2015-01-21 01:58:14

标签: python ruby-on-rails ruby django

好的,所以我有一个后端用于在rails上用ruby编写的应用程序,我只是使用django在python中重写了后端,但它不起作用,因为日期时间格式不同。

所以在rails中格式化似乎是

2015-01-14 05:14:44 UTC

并在python中看起来像

2015-01-19T17:58:08.991Z

现在我的django模型看起来像

date = models.DateTimeField()

现在当我得到modelobject.date时,它需要与ruby on rails中的格式相同...我需要做什么来重新格式化日期时间?

2 个答案:

答案 0 :(得分:0)

您可以使用strptime模块中的datetime使用格式字符串从查询结果中获取兼容python的日期时间。

所以,你会做的事情如下:

from datetime import strptime

# ... your code ...

date = strptime(date, "%Y-%m-%d %H:%M:%S %Z")

在strptime https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime

上查看此内容以获取更多信息

查看此内容以获取更多格式选项: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

答案 1 :(得分:0)

您可以在模型上创建使用Python的datetime模块转换字符串的方法:

import datetime

# ... model definition ...

    def date_from_ruby_string(self, datestring):
        """set date field based on string in ruby format"""
        self.date = datetime.strptime(datestring, "%Y-%m-%d %h-%M-%S UTC")

    def ruby_string_from_date(self):
        """return string of date in ruby format"""
        return self.date.strftime("%Y-%m-%d %h-%M-%S UTC")