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

前端 未结 3 949
有刺的猬
有刺的猬 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条回答
  •  -上瘾入骨i
    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()
    

提交回复
热议问题