Using a Unicode format for Python's `time.strftime()`

前端 未结 3 936
有刺的猬
有刺的猬 2020-12-24 09:09

I am trying to call Python\'s time.strftime() function using a Unicode format string:

u\'%d\\u200f/%m\\u200f/%Y %H:%M:%S\'

(\\

相关标签:
3条回答
  • 2020-12-24 09:38

    You should read from a file as Unicode and then convert it to Date-time format.

    from datetime import datetime
    
    f = open(LogFilePath, 'r', encoding='utf-8')
    # Read first line of log file and remove '\n' from end of it
    Log_DateTime = f.readline()[:-1]
    

    You can define Date-time format like this:

    fmt = "%Y-%m-%d %H:%M:%S.%f"
    

    But some programming language like C# doesn't support it easily, so you can change it to:

    fmt = "%Y-%m-%d %H:%M:%S"
    

    Or you can use like following way (to satisfy .%f):

    Log_DateTime = Log_DateTime + '.000000'
    

    If you have an unrecognized symbol (an Unicode symbol) then you should remove it too.

    # Removing an unrecognized symbol at the first of line (first character)
    Log_DateTime = Log_DateTime[1:] + '.000000'
    

    At the end, you should convert string date-time to real Date-time format:

    Log_DateTime = datetime.datetime.strptime(Log_DateTime, fmt)
    Current_Datetime = datetime.datetime.now() # Default format is '%Y-%m-%d %H:%M:%S.%f'
    # Calculate different between that two datetime and do suitable actions
    Current_Log_Diff = (Current_Datetime - Log_DateTime).total_seconds()
    
    0 讨论(0)
  • 2020-12-24 09:40

    Many standard library functions still don't support Unicode the way they should. You can use this workaround:

    import time
    my_format = u'%d\u200f/%m\u200f/%Y %H:%M:%S'
    my_time   = time.localtime()
    time.strftime(my_format.encode('utf-8'), my_time).decode('utf-8')
    
    0 讨论(0)
  • 2020-12-24 09:43

    You can format string through utf-8 encoding:

    time.strftime(u'%d\u200f/%m\u200f/%Y %H:%M:%S'.encode('utf-8'), t).decode('utf-8')
    
    0 讨论(0)
提交回复
热议问题