【问题标题】:Datetime - String Round Trip [duplicate]日期时间 - 字符串往返 [重复]
【发布时间】:2016-02-01 12:42:33
【问题描述】:

这给了我一个字符串。如何返回日期时间对象,以便进行一些日期算术等?

from datetime import datetime, timezone
s = datetime.now(timezone.utc).astimezone().isoformat()

这段代码 sn-p 生成了一个我很满意的字符串,但是我如何返回到datetime

2015-11-01T07:49:35.106745-08:00

【问题讨论】:

  • 您是否考虑过阅读文档或进行任何其他研究?
  • 将解决方案纳入您的程序是您的工作,这不是代码编写服务。

标签: python datetime python-3.x date-arithmetic date-comparison


【解决方案1】:

这可行,但它比我想看到的要忙。

dt = datetime.strptime(s[:-3]+s[-2:], "%Y-%m-%dT%H:%M:%S.%f%z")
print(dt)

【讨论】:

    【解决方案2】:

    在进行日期运算之前不要使用isoformat() 转换时间。

    试试这个:

    import datetime, time
    
    d0 = datetime.datetime.now()
    time.sleep(0.1)
    d1 = datetime.datetime.now()
    
    print('trip began:{}'.format(d0.isoformat()))
    print('trip ended:{}'.format(d1.isoformat()))
    delta = d1 - d0
    print('that took {} seconds'.format(delta.total_seconds()))
    

    以上内容对于时区和夏令时没有做正确的事情,但你最初的问题似乎有这部分工作:

    datetime.now(timezone.utc).astimezone()

    样本输出:

    trip began:2015-11-01T08:52:28.326764
    trip ended:2015-11-01T08:52:29.331763
    that took 1.004999 seconds
    

    【讨论】:

    • 我想要一个人类可读的字符串作为时间戳。
    • @coding4fun 请提供示例输出。
    • 请看我编辑的帖子。我希望至少精确到毫秒。
    • 时间戳将被不同的机器使用。
    • 谢谢。本练习的目的是将时间戳作为人类可读的字符串保存到文本文件或数据库中,除此之外我不想保存任何其他数据。那么,如何将字符串解析回datetime
    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多