Convert mysql timestamp to epoch time in python

Convert mysql timestamp to epoch time in python - is there an easy way to do this?


Asked by: Hailey118 | Posted: 05-10-2021






Answer 1

Why not let MySQL do the hard work?

select unix_timestamp(fieldname) from tablename;

Answered by: Maria596 | Posted: 06-11-2021



Answer 2

converting mysql time to epoch:

>>> import time
>>> import calendar
>>> mysql_time = "2010-01-02 03:04:05"
>>> mysql_time_struct = time.strptime(mysql_time, '%Y-%m-%d %H:%M:%S')
>>> print mysql_time_struct
(2010, 1, 2, 3, 4, 5, 5, 2, -1)
>>> mysql_time_epoch = calendar.timegm(mysql_time_struct)
>>> print mysql_time_epoch
1262401445

converting epoch to something MySQL can use:

>>> import time
>>> time_epoch = time.time()
>>> print time_epoch
1268121070.7
>>> time_struct = time.gmtime(time_epoch)
>>> print time_struct
(2010, 3, 9, 7, 51, 10, 1, 68, 0)
>>> time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time_struct)
>>> print time_formatted
2010-03-09 07:51:10

Answered by: Marcus326 | Posted: 06-11-2021



Answer 3

If you don't want to have MySQL do the work for some reason, then you can do this in Python easily enough. When you get a datetime column back from MySQLdb, you get a Python datetime.datetime object. To convert one of these, you can use time.mktime. For example:

import time
# Connecting to database skipped (also closing connection later)
c.execute("SELECT my_datetime_field FROM my_table")
d = c.fetchone()[0]
print time.mktime(d.timetuple())

Answered by: Stella730 | Posted: 06-11-2021



Answer 4

I use something like the following to get seconds since the epoch (UTC) from a MySQL date (local time):

calendar.timegm(
   time.gmtime(
      time.mktime(
         time.strptime(t, 
                       "%Y-%m-%d %H:%M:%S"))))

More info in this question: How do I convert local time to UTC in Python?

Answered by: Grace489 | Posted: 06-11-2021



Similar questions

python - Convert to UTC Timestamp

# parses some string into that format. datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S") # gets the seconds from the above date. timestamp1 = time.mktime(datetime1.timetuple()) # adds milliseconds to the above seconds. timeInMillis = int(timestamp1) * 1000 How do I (at any point in that code) turn the date into UTC format? I've been ploughing through the API for what seems ...


python - Convert UTC Timestamp to a normal date & timr

I have a PostgreSql which creates a timestamp with timezone for every row. But now when i try to printout this timestamp I get the following : "2013-03-06 00:00:00+01:00" Firstly why says it 00:00:00 ? Secondly how could I convert it to such a thing: 06.03.2013 07:10:13 Or For Example : "12 sec ago", "1 day and a hour ago" Thank you Marvin


python convert human to timestamp

My date is in following format: 19/Jun/2014:00:03:09 How to I convert it to epoch timestamp in python? Note: I searched on date format in python, but could not find any format that matches above. Thanks.


python - Convert string to epoch timestamp

I have timestamps in the following format: date = Fri Nov 30 13:32:45 UTC 2012 Is there a way to convert this string to an epoch timestamp? I haven't been able to figure out how to convert this string? Here's what I have been trying: import datetime d = 'Fri Nov 30 13:32:45 UTC 2012' fmt = '%a %b %e %R %Y' print d.strftime(fmt)


How I do convert from timestamp to date in python?

I have this string '2015-04-08T07:52:00Z' and I wanna to convert it to '08/04/2015', how can I do this?


Convert date to timestamp in Python

I have a database containing dates formatted like: "2015-10-20 22:24:46". I need to convert these dates to UNIX timestamps (UTC), what's the easiest way to do it with Python?


Python convert date string to timestamp

I need to convert string type Wed, 18 May 2016 11:21:35 GMT to timestamp, in Python. I'm using: datetime.datetime.strptime(string, format) But I don't want to specify the format for the date type.


python - Pandas Timestamp - Cannot convert arg to a time error

I am trying to find the min() value between two points using between_time. I have created two columns that I would like to use as my start and end time to find the minimum value and add the output to a new column: This is a snip of the df: df[['Date_Time','d1_idx_last','Low']] Date_Time d1_idx_last Low Timestamp ...


Convert Cocoa timestamp in Python

I have a Cocoa timestamp (zero time of January 1st, 2001 00:00:00 UTC) that I need to convert in Python. When I use the following code it assumes a Unix timestamp input. Besides adding 31 years in seconds (Just under a billion seconds...) what's the best way to convert the time? import datetime print(datetime.datetime.fromtimestamp(int("495759456")).strftime('%Y-%m-%d %H:%M:%S')) The out...


python - Convert range to timestamp in Pandas

I have a column in a pandas data frame that goes from 0 to 172800000 in steps of 10. I would like to convert into datetime stamp with a specified date, beginning at midnight of that day. So, suppose, time = np.arange(0,172800000, 10) I would like to convert this in the following format: YYYY-MM-DD: HH:MM:SS.XXX The starting date should be


python - Pandas cannot convert input to timestamp error

I have two variables in the data set beginning date (format datetime64[ns]) and end date(format datetime64[ns]). I'm using following code to get the dates between beginning date and end date. pd.date_range(start = data['beginning_date'], end = data['end_date'], freq = 'D') but it's throwing following error. cannot convert input to timestamp why I'm getting...


Python, Pandas, convert Timestamp to Period

Lets consider the following DataFrame: date_range = pd.date_range(dt(2010,1,1), dt(2010,1,31), freq='1D') df = pd.DataFrame(data = np.random.rand(len(date_range),2), index = date_range) If I group the datapoints by periods of 1 week and visualize the groups definition, I get: In: [1]:df.groupby(pd.TimeGrouper('W')).groups Out:[1]: {Timestamp('2010-01-03 00:00:00', fre...


python - How do i convert int64 to timestamp

import pandas as pd import urllib from pandas import DataFrame, Series import datetime url = 'https://chartapi.finance.yahoo.com/instrument/1.0/GOOG/chartdata;type=quote;range=10d/csv' urllib.request.urlretrieve(url, './data/goog.csv') GOOG= DataFrame(pd.read_csv("goog.csv")) GOOG['Timestamp']= datetime.datetime.fromtimestamp(GOOG['Timestamp']).strptime('%Y-%m-%d :%H:%M:%S) In this code i was a...


python - Convert pandas timestamp to month endate

I have the following code: #!/usr/bin/python import pandas as pd df = pd.read_excel(io='http://www.iea.org/gtf/download/Export_GTF_IEA.xls', sheetname='Data', skip_footer=5, ) df = df.drop('Unnamed: 2', axis=1) df = df.drop('Exit', axis=1) df = df.drop('Entry', axis=1) df = df.drop('MAXFLOW (Mm3/h)', axis=1) df = df.T df.to_csv('foo.csv', encoding='utf-8', sep='\t', header=False) # A...


Python - Convert Date string to UTC timestamp

I have a string that says "Oct. 2, 2017, midnight" and want to convert it to a UTC timestamp. Is there any good way to do this?


Can not convert 13 digit UNIX timestamp in python

Still new to this. I have tried to convert a 13 digit timestamp to something that you can read but to no luck. What i am doing is sampling temperature data from a building automation system. This is the code that i am working with. I am missing something very simple. Can i get a poke in the right direction. when_updated=driver.find_element_by_name("_lastUpdated") timestamp=when_updated.get_attribute("value"...


timestamp - Python - Convert 12 hour time in UTC in epoch format

I have a text box that displays time in following local time format - 04/03/2018 02:59:44 PM I'm using Selenium in python to get this time and convert it (local time) to epoch time (UCT). But it's converting to a time that is 11 hours 30 mins earlier (April 3, 2018 3:29:44 AM). here is my code: next_chk_dt = myDriver.find_element_by_xpath("(//input[@id='dateIDVisible'])[6]").get_attribute('value') # displa...


python - How will I convert epoch timestamp to get hour of the day?

This question already has answers here:


Python convert Timestamp to ISO 8601 revert to 1970 in loops

I am trying to do loops to convert a column of timestamp in a dataframe into ISO 8601 format. However, it keeps going back to the 1970 data with weird hour:minute:second. But if I just choose one timestamp and run the middle code "tz=... iso.format())", it works fine.


python - Timestamp doesn't convert from string into float

for post in posts: float(post[2]) # convert to float print(type(posts[0][2])) # print the type 1st row of the 2nd column print(posts[0][2]) The output is: <class 'str'> 1433213314.0 Why it hasn't converted into float?..


python - Convert to UTC Timestamp

# parses some string into that format. datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S") # gets the seconds from the above date. timestamp1 = time.mktime(datetime1.timetuple()) # adds milliseconds to the above seconds. timeInMillis = int(timestamp1) * 1000 How do I (at any point in that code) turn the date into UTC format? I've been ploughing through the API for what seems ...


Convert Unix Timestamp to human format in Django with Python

I'd like to a convert unix timestamp I have in a string (ex. 1277722499.82) into a more humanized format (hh:mm:ss or similar). Is there an easy way to do this in python for a django app? This is outside of a template, in the model that I would like to do this. Thanks. edit I'm using the python function time.time() to generate the timestamp. According to the doc: time.time()


python - How to convert current date to epoch timestamp?

How to convert current date to epoch timestamp ? Format current date: 29.08.2011 11:05:02


Convert a "string of time" into a timestamp without 3rd party modules in Python

This question already has answers here:


python - Convert UTC Timestamp to a normal date & timr

I have a PostgreSql which creates a timestamp with timezone for every row. But now when i try to printout this timestamp I get the following : "2013-03-06 00:00:00+01:00" Firstly why says it 00:00:00 ? Secondly how could I convert it to such a thing: 06.03.2013 07:10:13 Or For Example : "12 sec ago", "1 day and a hour ago" Thank you Marvin


How to convert a string based timestamp from Unix's date command to a Python date object?

A variety of programs output date formats according to the syntax of their Unix platforms date command. For example: Tue Nov 5 12:38:00 EST 2013. How can I easily convert this into a Python date object?


python - How do I convert a tempodb DataSet into actual numbers and get the timestamp?

I am reading values from my tempodb database using the following code: import datetime from tempodb import Client client = Client("key", "secret") start = datetime.datetime(2014, 3, 28) end = datetime.datetime(2014, 3, 29) data = client.read_key("custom", start, end, interval="1hour", function="mean") print data The code works fine, and it gets data points. However, it gets them in the f...


python convert human to timestamp

My date is in following format: 19/Jun/2014:00:03:09 How to I convert it to epoch timestamp in python? Note: I searched on date format in python, but could not find any format that matches above. Thanks.


python - Convert string to epoch timestamp

I have timestamps in the following format: date = Fri Nov 30 13:32:45 UTC 2012 Is there a way to convert this string to an epoch timestamp? I haven't been able to figure out how to convert this string? Here's what I have been trying: import datetime d = 'Fri Nov 30 13:32:45 UTC 2012' fmt = '%a %b %e %R %Y' print d.strftime(fmt)


How to convert string date to a epoch timestamp in python

I have a string date as 2015-03-25T00:00:00Z. How do I convert it to a unix epoch1426636800000.0 Are there any libraries in python to do that.


setting the gzip timestamp from Python

I'm interested in compressing data using Python's gzip module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed. Unfortunately, the output is different every tim...


java - log4j with timestamp per log entry

this is my log output INFO main digestemails - process inbox INFO main digestemails - checking for emails in c:\development\DCMail\email\KN-Source INFO main digestemails - digesting 003d01c95a7b_3446880_0202fea9@xxxx.com.eml INFO main digestemails - extracting attachments INFO main digestemails - no attachments or no attachments supported INFO main digestemails - updating database INFO main digestemails - e...


python - Django : Timestamp string custom field

I'm trying to create a custom timestamp field. class TimestampKey(models.CharField): __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): import time kwargs['unique'] = True kwargs['max_length'] = 20 kwargs['auto_created'] = True kwargs['editable']=False super(TimestampKey, self).__init__(*args, **kwargs) def to_python(self, ...


python - Django - String to Date - Date to UNIX Timestamp

I need to convert a date from a string (entered into a url) in the form of 12/09/2008-12:40:49. Obviously, I'll need a UNIX Timestamp at the end of it, but before I get that I need the Date object first. How do I do this? I can't find any resources that show the date in that format? Thank you.


python - Django - SQL Query - Timestamp

Can anyone turn me to a tutorial, code or some kind of resource that will help me out with the following problem. I have a table in a mySQL database. It contains an ID, Timestamp, another ID and a value. I'm passing it the 'main' ID which can uniquely identify a piece of data. However, I want to do a time search on this piece of data(therefore using the timestamp field). Therefore what would be ideal is to say: bet...


python - Convert to UTC Timestamp

# parses some string into that format. datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S") # gets the seconds from the above date. timestamp1 = time.mktime(datetime1.timetuple()) # adds milliseconds to the above seconds. timeInMillis = int(timestamp1) * 1000 How do I (at any point in that code) turn the date into UTC format? I've been ploughing through the API for what seems ...


datetime - Convert an RFC 3339 time to a standard Python timestamp

Is there an easy way to convert an RFC 3339 time into a regular Python timestamp? I've got a script which is reading an ATOM feed and I'd like to be able to compare the timestamp of an item in the ATOM feed to the modification time of a file. I notice from the


python - How to get latest timestamp in a column?

I have a timestamp column in my t1 table. The format is as: 2009-12-24 06:17:34 There are many entries as such. How do we query from views to get the latest timestamp


epoch timestamp converter with millennia range, python

is there an epoch time converter that can deal with millennia? time.gmtime(1000 * 365 * 24 * 60 * 60) throws ValueError: timestamp out of range for platform time_t


Write timestamp to file every hour in Python

I have a python script that is constantly grabbing data from Twitter and writing the messages to a file. The question that I have is every hour, I want my program to write the current time to the file. Below is my script. Currently, it gets into the timestamp function and just keeps printing out the time every 10 seconds. #! /usr/bin/env python import tweetstream import simplejson import urllib import time ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top