1

I have a string that says "Oct. 2, 2017, midnight" and want to convert it to a UTC timestamp.

Is there any good way to do this?

demluckycharms
  • 421
  • 1
  • 6
  • 17
  • are all the hours midnight? – usernamenotfound Jan 23 '18 at 19:37
  • Yeah all the hours are midnight. I actually did a little searching and found it seems to just be a normal date object with the format: 2017-10-02 00:00:00+00:00 – demluckycharms Jan 23 '18 at 19:39
  • Did you copy/paste your post title into Google and go through all the solutions? – dfundako Jan 23 '18 at 19:40
  • If all your data are "midnight" then it's trivial, just strip the last part of the string and pass it to `datetime.strptime()`. – r.ook Jan 23 '18 at 19:43
  • 1
    Possible duplicate of [Convert string date to timestamp in Python](https://stackoverflow.com/questions/9637838/convert-string-date-to-timestamp-in-python) – Scott Mermelstein Jan 23 '18 at 19:43
  • 1
    @ScottMermelstein I thought the same but the "midnight" string is kind of an interesting variant on the common problem. – r.ook Jan 23 '18 at 19:44

1 Answers1

2

Considering all your data is at midnight, the easiest way is to remove the , midnight string and convert it.

import datetime
import pytz
s = "Oct. 2, 2017, midnight"
dt = datetime.datetime.strptime(s.split(', midnight')[0], '%b. %d, %Y')
dt_utc = dt.astimezone(pytz.utc)

If there are other time indicated, you'll want to interpret the literals of the time and pass it onto strptime() accordingly.

r.ook
  • 13,466
  • 2
  • 22
  • 39