【问题标题】:Subtracting datetime in string format with datetime format用日期时间格式减去字符串格式的日期时间
【发布时间】:2021-09-06 17:50:20
【问题描述】:

我有 2 个变量。 一个是字符串格式的日期时间,一个是datetime.datetime格式的日期时间。

例如-

2021-09-06T07:58:19.032Z      # string
2021-09-05 14:58:10.209675    # datetime.datetime

我想以秒为单位找出这 2 次之间的差异。 我认为我们需要在日期时间中同时进行减法运算。 我很难将字符串转换为日期时间。 有人可以帮忙吗。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您可以使用strptime() 将字符串转换为datetime 对象

给定日期的示例:

from datetime import datetime

# Assuming this is already a datetime object in your code, you don't need this part
# I needed this part to be able to use it as a datetime object
date1 = datetime.strptime("2021-09-05 14:58:10.209675", "%Y-%m-%d %H:%M:%S.%f")

## The part where the string is converted to datetime object
# Since the string has "T" and "Z", we will have to remove them before we convert
formatted = "2021-09-06T07:58:19.032Z".replace("T", " ").replace("Z", "")
>>> 2021-09-06 07:58:19.032

# Finally, converting the string 
date2 = datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S.%f")
# Now date2 variable is a datetime object

# Performing a simple operation
print(date1 - date2)
>>> -1 day, 6:59:51.177675

【讨论】:

    【解决方案2】:

    通过strptime()str 转换为datetime,然后通过total_seconds() 以秒为单位获取两个日期时间对象的差异。

    from datetime import datetime, timezone
    
    # Input
    dt1_str = "2021-09-06T07:58:19.032Z"  # String type
    dt2 = datetime(year=2021, month=9, day=5, hour=14, minute=58, second=10, microsecond=209675, tzinfo=timezone.utc)  # datetime type
    
    # Convert the string to datetime
    dt1 = datetime.strptime(dt1_str, "%Y-%m-%dT%H:%M:%S.%f%z")
    
    # Subtract the datetime objects and get the seconds
    diff_seconds = (dt1 - dt2).total_seconds()
    print(diff_seconds)
    

    输出

    61208.822325
    

    【讨论】:

      【解决方案3】:

      您可以使用parser 而无需输入格式日期,如下所示:

      from dateutil import parser
      firs_date   = parser.parse("2021-09-06T07:58:19.032Z").timestamp()
      second_date = parser.parse("2021-09-05 14:58:10.209675").timestamp()
      firs_date - second_date
      

      【讨论】:

        【解决方案4】:

        您提到的第一个字符串时间可能是 rfc3339 格式。 一个名为 python-dateutil 的模块可以提供帮助

        import dateutil.parser    
        dateutil.parser.parse('2021-09-06T07:58:19.032Z')
        

        datetime 模块可以解析这种时间格式

        datetime.datetime.strptime("2021-09-06T07:58:19.032Z","%Y-%m-%dT%H:%M:%S.%fZ")
        

        但是这种方式在获取另一个时区的时间时可能会造成麻烦,因为它不支持时区偏移。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-10
          • 2023-03-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多