0

I am trying to convert a date to Unix time (which I ultimately need as a string) in Python 2.7. For example, 2017-06-29 (no time, but for purposes of converting to Unix should always be 00:00:00) should be '1498694400' of type string.

What is the cleanest, most efficient way to convert a YYYY-MM-DD to Unix string?

Insu Q
  • 403
  • 6
  • 13
  • 1
    85 results when searching for `[python] convert a date to Unix time` . Please realize that S.O. is a database of great Q/A, not just a one-way forum to ask Qs. Good luck. – shellter Jun 29 '17 at 02:20
  • 1
    AND, StackOverflow is about helping people fix their existing programming code. Please read http://stackoverflow.com/help/how-to-ask , http://stackoverflow.com/help/dont-ask , http://stackoverflow.com/help/mcve and take the [tour](http://stackoverflow.com/tour) before posting more Qs here. Good luck. – shellter Jun 29 '17 at 02:21
  • @shellter I appreciate your concern, but please don't be rude. I'm new here and haven't had an opportunity to contribute. In my search results, I didn't see where the date format was YYYY-MM-DD. Maybe I missed it. Or maybe you're assuming everyone knows how to adjust code when it's that similar. I'm new to programming, so I was hoping someone could provide a precise answer. – Insu Q Jun 29 '17 at 02:33

1 Answers1

4

As provided by katrielalex in this post:

>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0
Caladbolgll
  • 400
  • 1
  • 3
  • 15
  • `time` module alone is enough. `time.mktime(time.strptime('2017-06-29', '%Y-%m-%d'))` will do the job. Take a look at this super useful [reference](http://strftime.org/). – Shiva Jun 29 '17 at 02:23
  • @Shiva Thank you, this gets me pretty close. Though the unix time ends up being off by a few hours due to timezone difference. I'm thinking I just subtract the hours from the date before I convert it but I'm worried this hack might cause problems eventually. Is there a better way? – Insu Q Jun 29 '17 at 03:25