Search code examples
pythondatetimeutc

How to convert "01 January 2016" to UTC ISO format?


So I have the following string : " 01 January 2016" to UTC ISO date format ?

I'm using arrow module and the following code, but it's full of errors, and I was thinking that may be, there was a smaller more elegent solution as python encourages elegant and easier ways to do things, anyways here's my code :

updateStr = " 01 January 2016" #Note the space at the beginning
dateList = updateStr.split[' ']
dateDict = {"day" : dateList[1],"month": months.index(dateList[2])+1, "year" : dateList[3]}
dateStr = str(dateDict['day']) + "-" + str(dateDict["month"]) + "-" + str(dateDict["year"])
dateISO = arrow.get(dateStr, 'YYYY-MM-DD HH:mm:ss')

Please help me I have to convert it to the UTC ISO formats, Also months is a list of months in the year .


Solution

  • You can use datetime:

    >>> updateStr = " 01 January 2016"
    >>> import datetime as dt
    >>> dt.datetime.strptime(updateStr, " %d %B %Y")
    datetime.datetime(2016, 1, 1, 0, 0)
    >>> _.isoformat()
    '2016-01-01T00:00:00'
    

    Keep in mind that is a 'naive' object without a timezone. Check out pytz to deal with timezones elegantly, or just add an appropriate utcoffset to the datetime object for UTC.