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?

3
  • 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. Commented Jun 29, 2017 at 2:20
  • 1
    AND, StackOverflow is about helping people fix their existing programming code. Please read stackoverflow.com/help/how-to-ask , stackoverflow.com/help/dont-ask , stackoverflow.com/help/mcve and take the tour before posting more Qs here. Good luck. Commented Jun 29, 2017 at 2: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. Commented Jun 29, 2017 at 2:33

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.