子类化datetime.datetime [英] Subclassing datetime.datetime

查看:74
本文介绍了子类化datetime.datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑创建一个python datetime子类,该类在创建时会提供默认时区。

I'm looking into creating a python datetime-subclass which provides a default timezone when created.

为了使这个问题简单,让我们假设我总是想要将我的日期时间硬编码为UTC。

For the sake of keeping this question simple, let's assume I always want to hard-code my datetimes to be in UTC.

我不知道以下原因为何:

I can't figure out why the following works:

import datetime, dateutil.tz

def foo(*args, **kwargs):
    kwargs['tzinfo'] = dateutil.tz.tzutc()
    return datetime.datetime(*args, **kwargs)

但以下操作无效:

class Foo(datetime.datetime):
    def __init__(self, *args, **kwargs):
        kwargs['tzinfo'] = dateutil.tz.tzutc()
        super(Foo, self).__init__(*args, **kwargs)

运行第一种方法给我期望的datetime对象:

Running the first method gives me the datetime object I expect:

>>> foo(2012, 11, 10)
datetime.datetime(2012, 11, 10, 0, 0, tzinfo=tzutc())
>>> foo(2012, 11, 10).tzinfo is None
False

但是创建实例

>>> Foo(2012, 11, 10)
Foo(2012, 11, 10, 0, 0)
>>> Foo(2012, 11, 10).tzinfo is None
True

关于什么的任何想法

谢谢!

推荐答案

提供解决方案,如为什么不能为子类datetime.date 所述。完整,这要感谢 dano 的链接。

Providing the solution, as explained in Why can't I subclass datetime.date? for the sake of completeness, thanks to dano for the link.

由于datetime对象是不可变的,因此必须在新功能中实现额外的功能:

The extra functionality has to be implemented in new since the datetime object is immutable:

class Foo(datetime.datetime):
    def __new__(cls, *args, **kwargs):
        kwargs['tzinfo'] = dateutil.tz.tzutc()
        return datetime.datetime.__new__(cls, *args, **kwargs)

这篇关于子类化datetime.datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆