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

前端 未结 4 633
失恋的感觉
失恋的感觉 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)

    0 讨论(0)
  • 2020-12-24 12:47

    Try datetime.strptime().

    See: http://docs.python.org/library/datetime.html#datetime.datetime.strptime

    0 讨论(0)
  • 2020-12-24 12:48

    The Short. No.

    Locale information is not used by ctime().

    Note: When using time.ctime() & datetime.fromtimestamp() you might run into a historical issue when converting local timezones too. as stated in the comments of these answers here and here

    The Long.

    Alternatively, If you need a "Date & Time" that you can format there are many ways using datetime, time.strftime, also, even using python pandas, and here posix_time, and lastly as mention on the other answers here datetime.strptime.

    Known Date Differences

    If you are not worried about timezones or the Julian Calendar, Ambiguous Times or converting to localtime using UNIXTIMESTAMP, looking to use EPOCH Time, be sure to specify Notable epoch dates in computing and this for unix

    Which I thank Matt on this thread for the

    "Please stop calling it "epoch time" when you mean Unix Time".......

    My usage

    Now as crazy as all that was, its not that bad. I have worked with many companies before, and this usually never comes up in the work place, as it usually has been dealt with.

    So, aside from all that...This is My Personal Favorite:

    I use this for my own stuff: time.strftime

    from time import strftime
    
    print(strftime('%Y%m%d_%H%M%S'))
    

    Which I Return: Year, Month, Day, _, Hour, Minute, Second

    20180827_021106
    

    Which I use in a function:

    def _now():
        """The Module Reports A Formatted Time."""
        ymd = (strftime('%Y%m%d_%H%M%S'))
        return ymd
    

    Just something simple that keeps my logs in order.

    0 讨论(0)
  • 2020-12-24 12:51

    Just use %c:

    datetime.datetime.strptime(time.ctime(), "%c")
    
    0 讨论(0)
提交回复
热议问题