简体   繁体   English

检查日期时间对象中是否提供秒或微秒

[英]Check if second or microsecond were provided in a datetime object

Is there a way to determine for a python datetime object if time attributes were included at the time the object was created?有没有办法确定 python datetime 对象在创建对象时是否包含时间属性? In particular, I would like to know if minutes, seconds or microseconds were provided.特别是,我想知道是否提供了分钟、秒或微秒。

For example, the following:例如,以下内容:

from datetime import datetime
d = datetime(2020,1,24)
# datetime.datetime(2020, 1, 24, 0, 0)
d.microsecond
# 0

# ideally, if function "has_seconds()" did exist...
if not d.has_seconds():
     d = d.replace(second=59)

I am working on a function where I receive a datetime object and I need to fill-in any information that was not provided originally.我正在处理一个接收日期时间对象的函数,我需要填写最初未提供的任何信息。 However, datetime assumes a value 0 for all time attributes that were not provided originally.但是,对于最初未提供的所有时间属性,datetime 假定值为 0。 Unfortunately, 0 is valid for hours, minutes, seconds and microseconds, so I cannot use that to check.不幸的是,0 对小时、分钟、秒和微秒有效,所以我不能用它来检查。

I am using Python 3.7, in case it's of relevance.我正在使用 Python 3.7,以防万一。

This isn't going to be possible with a datetime.datetime instance.这对于datetime.datetime实例是不可能的。 As you note, the constructor automatically fills in missing values with 0 .正如您所注意到的,构造函数会自动用0填充缺失值。 Furthermore, there are other ways to create an instance of datetime.datetime beyond its constructor.此外,除了构造函数之外,还有其他方法可以创建datetime.datetime的实例。 There's no meaningful distinction between instances created by these various methods.这些不同方法创建的实例之间没有有意义的区别。 If they have the same underlying value, they are equivalent and indistinguishable, by design.如果它们具有相同的潜在价值,则它们在设计上是等效且无法区分的。 In other words, the datetime module is designed to actively discourage what you are trying to do.换句话说, datetime模块旨在积极阻止您尝试做的事情。

Without knowing more about your specific use-case and why you need this behavior, it's difficult to suggest an alternative.如果不了解更多关于您的特定用例以及您为什么需要这种行为,就很难提出替代方案。

However, if you have control over the code that calls your function, your best bet is probably to define and accept your own datetime.datetime -like class that offers a similar constructor, but which does not implicitly replace unspecified values with 0 .但是,如果您可以控制调用您的函数的代码,那么最好的办法可能是定义并接受您自己的类似datetime.datetime的类,该类提供类似的构造函数,但不会隐式地用0替换未指定的值。 Callers of your function would have to pass instances of your class instead of datetime.datetime .你的函数的调用者必须传递你的类的实例而不是datetime.datetime Once you have applied your custom "missing value" logic, you can create a fully-populated datetime.datetime object and proceed.应用自定义“缺失值”逻辑后,您可以创建一个完整填充的datetime.datetime对象并继续。

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

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