How to convert `ctime` to `datetime` in Python?

前端 未结 4 645
失恋的感觉
失恋的感觉 2020-12-24 12:21
import time
t = time.ctime()

For me at the moment, t is \'Sat Apr 21 11:58:02 2012\'. I have more data like this.

4条回答
  •  时光取名叫无心
    2020-12-24 12:32

    You should use strptime: this function parses a string representing a time according to a format. The return value is a struct_time.

    The format parameter defaults to %a %b %d %H:%M:%S %Y which matches the formatting returned by ctime().

    So in your case just try the following line, since the default format is the one from ctime:

    import datetime
    import time
    
    datetime.datetime.strptime(time.ctime(), "%a %b %d %H:%M:%S %Y")
    

    Returns: datetime.datetime(2012, 4, 21, 4, 22, 00)

提交回复
热议问题