代码之家  ›  专栏  ›  技术社区  ›  Mark Smith

python 3.6-将“yyyy-mm-dd”字符串作为日期时间数据类型分配给变量?

  •  0
  • Mark Smith  · 技术社区  · 7 年前

    本质上,我从未(从字符串)转换过日期时间数据类型并将其存储为python中的变量,我也从未见过这样做,在其他地方……

    从概念上讲,我希望能够做到以下几点:

    todays_date = '2018-06-11' # assign a date string to a variable
    
    todays_date = date(todays_date) # convert the date string to a date datatype
    

    if todays_date == date.today():
    
        do something...
    

    或与时间相似,例如

    stored_time = '18:03:23' # assign time to a variable as a string
    
    stored_time = time(stored_time) # convert the string to a time datatype
    
    if stored_time - now() > (03:00:00):
    
        do something...
    

    任何帮助都将不胜感激!

    多亏了下面来自muli的答案,我可以使用下面的方法将字符串指定为日期时间变量值:

    msg[3] = datetime.strptime(msg[3],"%Y-%m-%d")  #  YYYY-MM-DD
    msg[4] = datetime.strptime(msg[4], "%H:%M:%S.%f")  # HH:MM:SS.sss
    
    1 回复  |  直到 7 年前