I am working with a series of string representations of timestamps returned by time.asctime() in Python. The documentation states:
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: 'Sun Jun 20 23:21:05 1993'. The day field is two characters long and is space padded if the day is a single digit, e.g.: 'Wed Jun 9 04:26:40 1993'.
I've referenced Unicode Technical Standards to determine how I can instruct an instance of Swift's DateFormatter
how to interpret the string and create a Date
.
The UTS is very clear, but my Date
object still unwraps to nil
:
let dateAsString = measurement[2]
print("Date as string: \(dateAsString)")
let df = DateFormatter()
df.dateFormat = "E MMM dd HH:mm:ss y"
let date = df.date(from: dateAsString)
print("Date: \(String(describing: date))")
Output:
Date as string: Thu Oct 20 17:53:06 2022
Date: nil
Date as string: Thu Oct 20 17:53:06 2022
Date: nil
Date as string: Thu Oct 20 17:53:16 2022
Date: nil
When printing dateAsString
to console output, I did not notice that there is a single trailing whitespace after the year. Adjusting the Unicode format string to the following solved the problem:
df.dateFormat = "EEE MMM d HH:mm:ss y " // <- observe the extra space