user1673206
user1673206

Reputation: 1711

Converting between time formats

Is there a way to convert time from the year_month_day-hh_mm_ss to timestapm (in milliseconds since 1971) with DateUtils? or some other library..

thanks.

Upvotes: 1

Views: 166

Answers (4)

Anand Tripathi
Anand Tripathi

Reputation: 16146

You can use timedelta

from datetime import timedelta
year = timedelta(days=(2017-1971)*365)#number of days from 1971 to 2017
mili_sec = (year.total_seconds())*1000#you will get total_seconds just mulitply with 1000 to get milliseconds

OUTPUT

1450656000000.0

OR

You wanted difference from a particular date.Ex from 1971-01-01 to 2017-03-16-14:08:10

from datetime import datetime
new_day = datetime.strptime("2017_03_16-14:08:10", "%Y_%m_%d-%H:%M:%S")
old_day = datetime.strptime("1971_01_01-00:00:00", "%Y_%m_%d-%H:%M:%S")
diff_day_milliseconds = ((new_day - old_day).total_seconds())*1000

OUTPUT

1458137290000.0

Upvotes: 0

peteredhead
peteredhead

Reputation: 2804

Have a look at the Python datetime and time modules.

from datetime import datetime
d = datetime.strptime("2017_03_16-14:08:10", "%Y_%m_%d-%H:%M:%S")

This will create a datetime object of d

Then use mktime from Python's time module to get your timestamp

import time
time.mktime(d.timetuple())*1000

The *1000 is required to convert from seconds to milliseconds.

Also, do you mean 1971 or the Unix epoch (Jan 01 1970)?

Upvotes: 2

Alex
Alex

Reputation: 1522

You can parse the time with strptime, then you can get the time since epoch time in milliseconds by using strftime to format only seconds. Multiply by 1000 to get milliseconds.

converted_time.strftime("%s") * 1000

Upvotes: 0

Gustav Rasmussen
Gustav Rasmussen

Reputation: 3961

Try the arrow module found at the following URL: https://pypi.python.org/pypi/arrow

Upvotes: 0

Related Questions