-2

I have a date stored as a string:-

16/07/2014 13:00:00

I want to convert this into timestamp.

Also from timestamp to this format again.

Please suggest the best possible way to do this in python.

abhinsit
  • 3,214
  • 4
  • 21
  • 26
  • It has been asked before, except for a different format of time and not saving the object as a string for later use! I believe this question could add a little depth to some previous responses – KyleM Sep 17 '14 at 09:45
  • @KyleM so how many do you think there should be? One for every possible combination of order and delimiter? Then multiplied by a separate answer for each of printing straight away and "saving" as a named variable? What about if the OP wants to put it in a list, should that be a separate set of answers, too? Or in a tuple, or a dictionary, or ...? Programming is about taking general tools and applying them to specific situations. – jonrsharpe Sep 17 '14 at 09:52
  • @jonrsharpe, you are very right! However, maybe this question will clarify how the break up of the data works by providing some contrast to other questions, and provide avenue for an example of how to go back to a string in a required format, all in one place. Again, you are very entitled to your valid opinion, my belief however is that this does add some depth. – KyleM Sep 17 '14 at 09:56

3 Answers3

2

You can use datetime to handle combined dates and times. You could parse this string using datetime.strptime but then you'd have to manually select the formatting.

Alternatively you can use the dateutil package which has a parser which can intelligently guess the string format and return a datetime object, as shown below:

from dateutil import parser

s = '16/07/2014 13:00:00'

d = parser.parse(s)

print(d)
# 2014-07-16 13:00:00

print(type(d))
# datetime.datetime
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
1

The documentation to look into this deeper is here

The functions you are looking for are time.strptime(string[, format]) to go from string to timestamp, and then from timestamp to string is time.strftime(format[, t])

Here is an example for your format:

>>> from datetime import datetime
>>> 
>>> date_object = datetime.strptime('16/07/2014 13:00:00', '%d/%m/%Y %H:%M:%S')
>>> print date_object
2014-07-16 13:00:00

The to go back to your format (I have used gmtime() to get the current time to show you can convert any datetime to your desired format)

>>> from time import gmtime, strftime
>>> date_string = strftime("%d/%m/%Y %H:%M:%S", gmtime())
>>> print date_string
17/09/2014 09:31:00
KyleM
  • 508
  • 2
  • 4
  • 11
1

Your best bet is the datetime library: https://docs.python.org/2/library/datetime.html

import datetime
mytime='16/07/2014 13:00:00'
pythontime=datetime.datetime.strptime(mytime, '%d/%m/%Y %H:%M:%S')
stringtime=pythontime.strftime('%d/%m/%Y %H:%M:%S')

Enjoy!

Malcolm Murdoch
  • 1,075
  • 6
  • 9