简体   繁体   English

日期时间:在 isoformat() 中强制微秒输出

[英]datetime: force microsecond output in isoformat()

I just posted a question about Google Drive date formats, that I actually found a solution to.我刚刚发布了一个关于 Google Drive 日期格式的问题,我实际上找到了解决方案。 Essentially, Google Drive documentation states that it requires dates to be specified in the RFC 3339 format.本质上,Google Drive 文档声明它需要以 RFC 3339 格式指定日期。 However, it requires the full or long format explicitly, even when milliseconds are zero.但是,它明确要求完整或长格式,即使毫秒为零也是如此。 Is there a way to force the datetime isoformat() method to output milliseconds, even when zero?有没有办法强制 datetime isoformat() 方法输出毫秒,即使为零? I'd rather not enforce my own datetime specification using strftime, but if the only solution is to use the following strftime format, then so be it.我宁愿不使用 strftime 强制执行我自己的日期时间规范,但如果唯一的解决方案是使用以下 strftime 格式,那么就这样吧。

d.strftime("%Y-%m-%dT%H:%M:%S.%f+00:00")

Here is the implementation of datetime isoformat():这是 datetime isoformat() 的实现:

static char *
isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
{
    int x;
    int us = DATE_GET_MICROSECOND(dt);

    x = PyOS_snprintf(buffer, bufflen,
                      "%02d:%02d:%02d",
                      DATE_GET_HOUR(dt),
                      DATE_GET_MINUTE(dt),
                      DATE_GET_SECOND(dt));
    assert(bufflen >= x);
    if (us)
        x += PyOS_snprintf(buffer + x, bufflen - x, ".%06d", us);
    assert(bufflen >= x);
    return buffer + x;
}

Doesn't look like you can do anything to enforce microseconds in the output string.看起来您无法做任何事情来强制输出字符串中的微秒。

If you're using Python 3.6+, you can pass the timespec parameter to isoformat()如果您使用的是 Python 3.6+,则可以将timespec参数传递给timespec isoformat()

The function ends up calling _format_time , where you can see the supported values for the parameter:该函数最终调用_format_time ,您可以在其中查看参数的支持值:

specs = {
    'hours': '{:02d}',
    'minutes': '{:02d}:{:02d}',
    'seconds': '{:02d}:{:02d}:{:02d}',
    'milliseconds': '{:02d}:{:02d}:{:02d}.{:03d}',
    'microseconds': '{:02d}:{:02d}:{:02d}.{:06d}'
}

This will force the value to be rendered even if the specific part is zero即使特定部分为零,这也将强制呈现值

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

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