Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date, datetime to timestamp

How can I produce a timestamp to millisecond accuracy from a date or datetime in Python?

There are an overwhelming number of methods and ways of doing this, and I'm wondering which is the most Pythonic way.

like image 283
Humphrey Bogart Avatar asked May 03 '10 00:05

Humphrey Bogart


People also ask

How do I convert a date to time stamp?

Use the getTime() method to convert a date to a timestamp, e.g. new Date(). getTime() . The getTime method returns the number of milliseconds elapsed between the 1st of January, 1970 and the given date.

How do I convert UTC timestamp to date?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.

How do I convert datetime to numbers?

Method 2: Using datetime. In this method, we are using strftime() function of datetime class which converts it into the string which can be converted to an integer using the int() function. Returns : It returns the string representation of the date or time object.


1 Answers

The following has worked for my purposes:

To datetime from millisecond timestamp

import datetime
timestamp #=> 1317912250955
dt = datetime.datetime.fromtimestamp(time/1000.0)
dt #=> datetime.datetime(2011, 10, 6, 10, 44, 10, 955000)

From datetime to millisecond timestamp

import time
dt #=> datetime.datetime(2011, 10, 6, 10, 44, 10, 955000)
timestamp = int((time.mktime(dt.timetuple()) + dt.microsecond/1000000.0)*1000)
timestamp #=> 1317912250955
like image 110
Shock3nAw Avatar answered Sep 30 '22 10:09

Shock3nAw