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

前端 未结 4 655
失恋的感觉
失恋的感觉 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: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.

提交回复
热议问题