-3

The UTC time is formatted like this

  "Tue 24 Dec 2013  5:53 AM UTC"

Is there a built-in function to convert it to milliseconds or I have to write my own scripts for it?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
nan
  • 1,131
  • 4
  • 18
  • 35

1 Answers1

0

The obvious answer, using the time module with time.strptime() doing the parsing:

import time

timetup = time.strptime(inputstring, '%a %d %b %Y %I:%M %p %Z')
milliseconds = time.mktime(timetup) * 1000

This does require that you don't set the locale in Python, leaving it at the default C locale, or only set it to a English locale. The %a and %b formatters only look for strings that match the configured locale, and only the C and English locales match the input strings.

Demo:

>>> import time
>>> inputstring = "Tue 24 Dec 2013  5:53 AM UTC"
>>> timetup = time.strptime(inputstring, '%a %d %b %Y %I:%M %p %Z')
>>> time.mktime(timetup) * 1000
1387864380000.0

This does assume that by milliseconds you meant milliseconds since the UNIX epoch.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • OK. thanks. I did a search before posting this question. What I found were solutions for parsing strings with only numbers as input. I thought I would have to convert those "Mon""Tue" or months like "Jan" "Feb" to numbers first before using the function. Thanks – nan Jan 27 '14 at 13:03
  • Do include in your post what you found while trying to solve the problem on your own; it helps us determine if there is a duplicate post here or that you at least tried to find a solution elsewhere first. – Martijn Pieters Jan 27 '14 at 13:05