-4

Possible Duplicate:
Converting string into datetime

Example '12:00:01 AM'

I want to set variables : hr = 12, min= 00,s= 01,t = AM

Please help me out to compare time , I comparing ( example: 1:10:00 PM < '12:00:01 AM')

With < sign result produced is not always correct.

So I am trying developing code to compare time by setting variable

But it could be directly available by any function please let me know

Otherwise please help me out to set variables

Community
  • 1
  • 1
user1103116
  • 1
  • 1
  • 2
  • The answers at http://stackoverflow.com/questions/466345/converting-string-into-datetime may help you. – AlG Jan 13 '12 at 14:19
  • What code have you tried to implement, and where is it not working properly? – Makoto Jan 13 '12 at 14:20

1 Answers1

0

It is easier to compare dates and times using datetime objects rather than setting variables representing the hour, minutes, seconds, etc and doing the calculation yourself.

Using datetime.strptime from the standard library:

import datetime as dt

date1 = dt.datetime.strptime('12:00:01 AM', '%I:%M:%S %p')
date2 = dt.datetime.strptime('1:10:01 PM', '%I:%M:%S %p')   

print(date1)
# 1900-01-01 12:00:01

print(date2)
# 1900-01-01 13:10:01

print(date2 < date1)
# False

Or, using dateutil:

import dateutil.parser as parser

date1 = parser.parse('12:00:01 AM')
date2 = parser.parse('1:10:00 PM')

print(date1)
# 2012-01-13 00:00:01

print(date2)
# 2012-01-13 13:10:00

print(date2 < date1)
# False

The above shows it is not necessary to set variables for the hours, minutes and seconds. However, it is easy to access that information from a datetime.datetime object as well:

In [44]: x = dt.datetime.strptime('12:00:01 AM', '%I:%M:%S %p')

In [45]: x.hour, x.minute, x.second
Out[45]: (0, 0, 1)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677