Python - convert string to datetime


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

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dmontgomAuthor Commented:
What if the -0700 Is dymanic?  If it is not always -0700?
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

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.