Wednesday, 15 January 2014

ruby - DateTime to Time conversion -



ruby - DateTime to Time conversion -

i have 2 datetimes , need determine seconds between them. created like:

date_time1 = datetime.strptime("01-15-2014 01:11:12 pm", '%m-%d-%y %l:%m:%s') date_time2 = datetime.now

so this:

date_time1: 2014-01-15t01:11:12+00:00 date_time2: 2014-01-16t00:11:12+10:00

how find seconds between 2 datetimes? have tried converting time .to_time function not working me because timezone apparently not set.

any help appreciated.

thanks

to_time does work. converts both times local timezone, makes no difference when subtracting them. works:

date_time2.to_time - date_time1.to_time

your real problem you're not parsing pm, why difference ends off 12 hours! @ example

date_time1 = datetime.strptime("01-15-2014 01:11:12 pm", '%m-%d-%y %l:%m:%s') # date_time1: 2014-01-15t01:11:12+00:00

you asking 1:11 pm utc, telling date_time1 1:11 am. need add together format string

'%m-%d-%y %l:%m:%s %p'

here's illustration timezone if you're still skeptical.

d1 = datetime.now #<datetime: 2014-06-18t11:47:22-04:00 ((2456827j,56842s,704352659n),-14400s,2299161j)> d1.to_time - datetime.strptime("06-18-2014 03:47:00 pm", '%m-%d-%y %l:%m:%s %p').to_time # 22.704352659

note 3:47 pm utc 11:47 in utc-4 (the timezone of d1), ~22 seconds right answer.

edit

if, however, want alter them in same timezone before calculating offset, can following:

date_time2.to_time - (date_time1 - date_time2.offset).to_time

ruby datetime time

No comments:

Post a Comment