390

I am getting a response from the rest is an Epoch time format like

start_time = 1234566
end_time = 1234578

I want to convert that epoch seconds in MySQL format time so that I could store the differences in my MySQL database.

I tried:

>>> import time
>>> time.gmtime(123456)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=2, tm_hour=10, tm_min=17, tm_sec=36, tm_wday=4, tm_yday=2, tm_isdst=0)

The above result is not what I am expecting. I want it be like

2012-09-12 21:00:00

Please suggest how can I achieve this?

Also, Why I am getting TypeError: a float is required for

>>> getbbb_class.end_time = 1347516459425
>>> mend = time.gmtime(getbbb_class.end_time).tm_hour
Traceback (most recent call last):
  ...
TypeError: a float is required
martineau
  • 112,593
  • 23
  • 157
  • 280
user1667633
  • 4,169
  • 2
  • 15
  • 21

9 Answers9

453

To convert your time value (float or int) to a formatted string, use:

import time

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

For example:

import time

my_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))

print(my_time)
Alan W. Smith
  • 23,261
  • 4
  • 66
  • 92
ron rothman
  • 16,048
  • 6
  • 38
  • 40
  • 3
    time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517491247)) '44671-02-17 11:44:07' why? – user1667633 Sep 13 '12 at 06:35
  • 5
    Where did the time "1347517491247" come from in your example? Is it a real time value you're using? – ron rothman Sep 13 '12 at 06:39
  • actually i am getting that value from bigbluebutton server – user1667633 Sep 13 '12 at 06:43
  • 24
    time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517491.247)) '2012-09-13 08:24:51' Your value is epoch in ms – MatthieuW Sep 13 '12 at 08:21
  • 2
    see http://docs.python.org/2/library/time.html#time.strftime for more info in the format string – georg Jul 27 '13 at 21:01
  • `%a` to `%z` [table with **examples**](https://docs.python.org/library/datetime.html#strftime-and-strptime-behavior). See also [datetime vs. time](https://stackoverflow.com/q/7479777/673991) – Bob Stein Aug 17 '18 at 16:07
  • `time.gmtime(1347517370)` for utc time. – Quad Coders Aug 07 '20 at 15:25
  • In conjunction with @jhon-didier-sotto answer: this solution works with milliseconds as well. Just divide the timestamp by 1000. `time.localtime(1347517370 / 1000)`. Works 60% of the time, every time! – Paul Tuckett Dec 09 '20 at 18:18
277

You can also use datetime:

>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%c')
  '2012-09-13 02:22:50'
hd1
  • 32,598
  • 5
  • 75
  • 87
png
  • 5,294
  • 2
  • 24
  • 15
  • 3
    in which timezone does this convert, what if I want to be in a specific timezone. ? – garg10may Jul 12 '16 at 09:29
  • 6
    @garg10may epoch time is always UTC offset 0, so the string would also be UTC offset 0. This is equilvalent to the Zulu timezone (+00:00). You can read more here: https://www.timeanddate.com/time/zones/z – Olivercodes Jan 10 '17 at 20:36
  • 10
    There is 'utcfromtimestamp' function to get UTC time in python 3. – vwvolodya Jan 04 '18 at 18:30
  • 1
    The advantage of using this answer is that the datetime version of `strftime()` supports more formatting placeholders, particularly %f for the microseconds porttion of the time. For reasons unknown, `time.strftime()` does not support that, although the microseconds can be represented in the float value that is input to `time.localtime()`. – Andreas Maier Aug 13 '19 at 04:39
  • 1
    Gives me this instead - `'“Sat Oct 31 18:30:00 2020” ` . Where as you mentioned - `'2012-09-13 02:22:50'` . It should be - `"%Y/%m/%d, %H:%M:%S"` – Akshay Hazari Dec 22 '20 at 04:44
  • Alternately, if you only need the datetime object simply datetime.datetime.fromtimestamp(epoch_value) will do the trick – Kamel Jan 05 '21 at 19:36
90
>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
'2012-09-13 14:22:50' # Local time

To get UTC:

>>> datetime.datetime.utcfromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
  '2012-09-13 06:22:50'
gsamaras
  • 69,751
  • 39
  • 173
  • 279
user799188
  • 13,097
  • 3
  • 31
  • 36
19

This is what you need

In [1]: time.time()
Out[1]: 1347517739.44904

In [2]: time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time()))
Out[2]: '2012-09-13 06:31:43'

Please input a float instead of an int and that other TypeError should go away.

mend = time.gmtime(float(getbbb_class.end_time)).tm_hour
pradyunsg
  • 16,339
  • 10
  • 39
  • 91
ronak
  • 1,580
  • 2
  • 19
  • 32
12

Try this:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1347517119))
'2012-09-12 23:18:39'

Also in MySQL, you can FROM_UNIXTIME like:

INSERT INTO tblname VALUES (FROM_UNIXTIME(1347517119))

For your 2nd question, it is probably because getbbb_class.end_time is a string. You can convert it to numeric like: float(getbbb_class.end_time)

dkamins
  • 20,856
  • 7
  • 51
  • 58
9

If you have epoch in milliseconds a possible solution is convert to seconds:

import time
time.ctime(milliseconds/1000)

For more time functions: https://docs.python.org/3/library/time.html#functions

8
#This adds 10 seconds from now.
from datetime import datetime
import commands

date_string_command="date +%s"
utc = commands.getoutput(date_string_command)
a_date=datetime.fromtimestamp(float(int(utc))).strftime('%Y-%m-%d %H:%M:%S')
print('a_date:'+a_date)
utc = int(utc)+10
b_date=datetime.fromtimestamp(float(utc)).strftime('%Y-%m-%d %H:%M:%S')
print('b_date:'+b_date)

This is a little more wordy but it comes from date command in unix.

user2899300
  • 81
  • 1
  • 1
5

First a bit of info in epoch from man gmtime

The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar  time.   When  inter-
       preted  as  an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
       Time (UTC).

to understand how epoch should be.

>>> time.time()
1347517171.6514659
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)

just ensure the arg you are passing to time.gmtime() is integer.

tuxuday
  • 2,843
  • 16
  • 18
0

Sharing an answer to clearly distinguish UTC and local time conversions. Use import datetime at the top before using the below methods.

Convert to datetime of local machine's timezone

datetime.datetime.fromtimestamp(1347517370)

Convert to datetime of UTC timezone

datetime.datetime.utcfromtimestamp(1347517370)

For both the above methods, if you wish to return a formatted date string, use the following code block

datetime.datetime.fromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
datetime.datetime.utcfromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
Keet Sugathadasa
  • 8,229
  • 2
  • 55
  • 69