Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the proper way to convert between mysql datetime and python timestamp?

according to http://dev.mysql.com/doc/refman/5.0/en/datetime.html. i got to find a way to convert the string value 'YYYY-MM-DD HH:MM:SS' to a timestamp int.

i looked up in python's doc.

i tried:

print(time.strptime('2013-01-12 15:27:43', '%Y-%m-%d %H:%M:%S'))   

python give me a result like this.

time.struct_time(tm_year=2013, tm_mon=1, tm_mday=12, tm_hour=15, tm_min=27, tm_sec=43, tm_wday=5, tm_yday=12, tm_isdst=-1)

i tried this to convert timestamp to YYYY-MM-DD HH:MM:SS format

print(time.strftime('%Y-%m-%d %H:%M:%S',time.time()))

python give me a type error.

i only use timestamp to calculate time and date, i hope there's already a way in python, simple and efficient , and don't have to create temp data.

according to the answer i write two methods. hope it would be helpful

import time

def convertTimestampToSQLDateTime(value):
    return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(value))

def convertSQLDateTimeToTimestamp(value):
    return time.mktime(time.strptime(value, '%Y-%m-%d %H:%M:%S'))
like image 332
Max Avatar asked Jan 12 '13 08:01

Max


People also ask

What is the correct datetime format for MySQL?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

Should I use datetime or TIMESTAMP MySQL?

To summarize, if you want to serve your date and time data the same way regardless of timezones, you can use the DATETIME type (which will also allow you to use all the date & type functions built in MySQL). Otherwise, you can use TIMESTAMP and serve the data on a per-timezone basis.

Is TIMESTAMP the same as datetime Python?

Timestamp is the pandas equivalent of python's Datetime and is interchangeable with it in most cases. It's the type used for the entries that make up a DatetimeIndex, and other timeseries oriented data structures in pandas. Value to be converted to Timestamp.


2 Answers

Happy to update this if I'm not properly understanding, but here are a few examples which may help. Note that this uses the datetime module instead of time.

>>> import datetime

Here we set up an example timestamp ts and a format f:

>>> ts = '2013-01-12 15:27:43'
>>> f = '%Y-%m-%d %H:%M:%S'

Similar to what you did above, we use the strptime function (from datetime.datetime) to convert our string into a datetime object based on the formatting parameter:

>>> datetime.datetime.strptime(ts, f)
datetime.datetime(2013, 1, 12, 15, 27, 43)

Now in reverse - here we use datetime.datetime.now() to get the current time as a datetime object:

>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 1, 12, 0, 46, 54, 490219)

In the datetime case, the strftime method is actually called on the datetime object itself, with the formatting parameter as an argument:

>>> now.strftime(f)   
'2013-01-12 00:46:54'

In your situation, the reason you were getting an error is because time.time() returns a float:

>>> time.time()
1357980846.290231

But time.strftime needs a time tuple, similar to what you had above. Without getting into the maddening spiral that is time, a function such as time.localtime() will return the aforementioned time tuple and will return as you expect:

>>> now = time.localtime()
>>> now
time.struct_time(tm_year=2013, tm_mon=1, tm_mday=12, tm_hour=0, tm_min=55, tm_sec=55, tm_wday=5, tm_yday=12, tm_isdst=0)
>>> f = '%Y-%m-%d %H:%M:%S'
>>> time.strftime(f, now)
'2013-01-12 00:55:55'
like image 156
RocketDonkey Avatar answered Oct 18 '22 23:10

RocketDonkey


I'm only adding this class to potentially save the next guy a little time. If anyone finds this useful, upvote RocketDonkey's answer.

## dev on v3.7.6

from datetime import datetime
from time import mktime, time


class Time:
    '''\
*Convenience class for easy format conversion*\n
Accepts time() float, datetime object, or SQL datetime str.\n
If no time arg is provided, object is initialized with time().\n
id kwarg can be used to keep track of objects.\n
Access formats as instance.t, instance.dt, or instance.sql.\
    '''

    f = '%Y-%m-%d %H:%M:%S'

    def __init__(self, *arg, id=None) -> None:
        self.id = id
        if len(arg) == 0:
            self.t = time()
            self.dt = self._dt
            self.sql = self._sql
        else:
            arg = arg[0]
            if isinstance(arg, float) or arg == None:
                if isinstance(arg, float):
                    self.t = arg
                else:
                    self.t = time()
                self.dt = self._dt
                self.sql = self._sql
            elif isinstance(arg, datetime):
                self.t = arg.timestamp()
                self.dt = arg
                self.sql = self._sql
            elif isinstance(arg, str):
                self.sql = arg
                if '.' not in arg:
                    self.dt = datetime.strptime(self.sql, Time.f)
                else:
                    normal, fract = arg.split('.')
                    py_t = datetime.strptime(normal, Time.f)
                    self.dt = py_t.replace(
                        microsecond=int(fract.ljust(6, '0')[:6]))
                self.t = self.dt.timestamp()

    @property
    def _dt(self) -> datetime:
        return datetime.fromtimestamp(self.t)

    @property
    def _sql(self) -> str:
        t = self.dt
        std = t.strftime(Time.f)
        fract = f'.{str(round(t.microsecond, -3))[:3]}'
        return std + fract

    def __str__(self) -> str:
        if self.id == None:
            return self.sql
        else:
            return f'Time obj "{self.id}": {self.sql}'


def test():
    def test_one(*arg):
        t = Time(*arg, id=type(*arg))
        print(t)
        print(t.t)
        print(t.dt)

    sql = '2020-01-22 15:30:33.433'
    time_float = 1579927395.3708763
    dt_obj = datetime.now()
    for datum in [sql, time_float, dt_obj, None]:
        test_one(datum)


if __name__ == '__main__':
    test()
like image 4
pocreagan Avatar answered Oct 18 '22 22:10

pocreagan