'How to convert Linux date string to Python Datetime

I am trying to convert the Linux date time 'Fri Feb 25 16:07:17 UTC 2022' to python datetime but not able to achieve the same. However, I am able to do using below code, but still looking for the right approach:

Input -> Fri Feb 25 16:07:17 UTC 2022

from datetime import datetime
linux_date="Fri Feb 25 16:07:17 UTC 2022"
arr=linux_date.split(' ')
py_str=f"{arr[1]+' '+arr[2]+' '+arr[5]+' '+arr[3]}"
py_str=(datetime.strptime(py_str, '%b %d %Y %H:%M:%S')).strftime("%Y-%m-%d %H:%M:%S")
py_str

Output -> '2022-02-25 16:07:17'



Solution 1:[1]

This should do it:

datetime.strptime(linux_date, '%a %b %d %H:%M:%S %Z %Y')
  • %a abbreviated day of week
  • %b abbreviated month name
  • '%d` day of month
  • %H:%M:%S - time as hours:minutes:seconds
  • %Z - timezone name
  • %Y - 4-digit year

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar