• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3719
  • Last Modified:

Python - convert string to datetime

Hi,

I have two strings that I want to convert into date and datetimes...
1) 05/15/2009
2) 20 May 2009 23:09:31 -0700

I am going the route of using datetime.datetime.fromtimestamp(time.mktime(time.strptime(dd, "%d %m %Y %H:%M:%S")))

please write the two lines of code that I need for each string I want to convert..

Thanks
0
dmontgom
Asked:
dmontgom
  • 3
1 Solution
 
HonorGodSoftware EngineerCommented:
Something like this perhaps.

I don't see anything that allows/supports the -700 though
datetime.datetime.fromtimestamp( time.mktime( time.strptime( '05/15/2009', '%m/%d/%Y' ) ) )
 
datetime.datetime.fromtimestamp( time.mktime( time.strptime( '20 May 2009 23:09:31 -0700', '%d %b %Y %H:%M%S ' ) ) )

Open in new window

0
 
HonorGodSoftware EngineerCommented:
If you have to match the "-0700", then the second would look like:

I made a mistake on line 3 above, it should have looked like line 3 here:


datetime.datetime.fromtimestamp( time.mktime( time.strptime( '20 May 2009 23:09:31 -0700', '%d %b %Y %H:%M:%S -0700' ) ) )
 
datetime.datetime.fromtimestamp( time.mktime( time.strptime( '20 May 2009 23:09:31', '%d %b %Y %H:%M:%S' ) ) )

Open in new window

0
 
dmontgomAuthor Commented:
What if the -0700 Is dymanic?  If it is not always -0700?
0
 
HonorGodSoftware EngineerCommented:
Then you would have to remove it...

That part of a date stamp is the local offset from GMT, so should stay the same, unless you are moving your machine.

One way to remove it would be shown below.

Thanks for the grade & points.

Good luck & have a great day
>>> ds = '20 May 2009 23:09:31 -0700'
>>> ds = ' '.join( ds.split( ' ' )[ 0:-1 ] )
>>> ds
'20 May 2009 23:09:31'
>>>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now