Converting unix timestamp string to readable date

Go To StackoverFlow.com

671

I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get a TypeError:

>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
2010-09-10 06:56
by VeryNewToPython
link to question for converting back too: https://stackoverflow.com/q/19801727/327303 - slushy 2018-11-08 17:54


998

Use datetime module:

from datetime import datetime
ts = int("1284101485")

# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
2010-09-10 07:09
by Michał Niklas
.fromtimestamp() might fail for past dates if a local timezone had different utc offset. You need a historic timezone database such as provided by pytz module (or your OS). Or just work in UTC and use .utcfromtimestamp() - jfs 2013-11-23 01:08
@J.F.Sebastian You've mentioned this might fail in a couple of comments - please could you elaborate as to why it would fail for a past dates/times? (Judging by the upvotes, many people both agree with you and see this as straightforward) Surely any unix timestamp has a simple equivalent date/time - davidhood2 2016-11-22 09:16
@davidhood2 take a system where python has no access to the tz database (Windows), set your local timezone to a timezone that had a different UTC offset in the past (e.g. Europe/Moscow), call fromtimestamp() with timestamps from the past (2011-). Compare the results with values computed using pytz. If it is unclear; ask a separate Stack Overflow question - jfs 2016-11-22 14:10
@davidhood2: I've posted my own answer that demonstrates the <code>pytz</code> solution - jfs 2016-11-23 16:31
An import point is this takes a timestamp in seconds since the epoch; if you have milliseconds you have to divide by 1000 as I just found out - wordsforthewise 2017-06-13 18:28
Is there an advantage of using strftime over "{:%Y-%m-%d %H:%M:%S}".format(dateobj) - Martin Thoma 2017-08-10 13:02
According to Python documentation __format__() is same as strftime() but I simply prefer strftime() - Michał Niklas 2017-08-11 09:19
If you are getting ValueError: year VALUE is out of range, that means you are working with milliseconds(Unix timestamp is 13 digits). The above function works only if Unix timestamp in seconds.

If you are working with milliseconds, divide that value by 1000.

https://stackoverflow.com/q/31548132/296055 - vardin 2017-10-30 09:44

What if I want to include milliseconds - User 2018-10-20 23:48
@User pass a float e.g., if you have 1234 milliseconds then pass 1.234 seconds (it is easy to divide by 1000 on the decimal system: just move the decimal dot 3 positions to the left) - jfs 2018-12-27 15:41


200

>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

Taken from http://seehuhn.de/pages/pdate

2010-09-10 06:59
by Daniel


138

The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

Where posix_time is the Posix epoch time you want to convert

2016-05-12 13:23
by rkachach
import datetime, pytz datetime.datetime(1990, 1, 1, tzinfo=pytz.utc - yauheni_selivonchyk 2017-06-23 18:09


69

>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'
2010-09-10 08:28
by John La Rooy
time.ctime() and time.localtime() might fail for past dates if a local timezone had different utc offset. You need a historic timezone database such as provided by pytz module (or your OS). Or just work in UTC and use time.gmtime(). datetime might provide wider date range so datetime.utcfromtimestamp() could be used instead of time functions - jfs 2013-11-23 01:30


51

There are two parts:

  1. Convert the unix timestamp ("seconds since epoch") to the local time
  2. Display the local time in the desired format.

A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:

#!/usr/bin/env python
from datetime import datetime
import tzlocal  # $ pip install tzlocal

unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)

To display it, you could use any time format that is supported by your system e.g.:

print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y"))  # print date in your format

If you do not need a local time, to get a readable UTC time instead:

utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))

If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:

local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))

On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):

#!/usr/bin/env python3
from datetime import datetime, timezone

utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))

Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:

#!/usr/bin/env python
import time

unix_timestamp  = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) 
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))  
2016-11-23 16:30
by jfs


34

For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:

import os, datetime

datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

Output:

'December 26, 2012'

2012-12-27 02:11
by Jared Burrows
Why was this down voted once? If you down voted, you should at least explain why you would down vote a correct answer - Jared Burrows 2013-10-08 00:04
I edited and added clarity. I used this and still use this code in order to print clear time stamps - Jared Burrows 2013-10-09 17:45
Who downvoted this again? Comment and explain instead of being appart of the issue - Jared Burrows 2015-02-06 14:59
My guess: it adds nothing to the accepted answer that already demonstrates both: .fromtimestamp() and .strftime() methods. Note: getmtime() returns a float already - jfs 2015-05-16 13:00
Another downvote? If you are going to downvote, at least say why - Jared Burrows 2015-06-09 03:15
Another downvote? If you are going to downvote, at least say why - Jared Burrows 2017-05-22 19:54


23

You can convert the current time like this

t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'

To convert a date in string to different formats.

import datetime,time

def createDateObject(str_date,strFormat="%Y-%m-%d"):    
    timeStamp = time.mktime(time.strptime(str_date,strFormat))
    return datetime.datetime.fromtimestamp(timeStamp)

def FormatDate(objectDate,strFormat="%Y-%m-%d"):
    return objectDate.strftime(strFormat)

Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')

Output 03-03-2013
2012-03-07 07:30
by Nick


15

Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:

Timestamps can be in two formats:

  1. 13 digits(milliseconds) - To convert milliseconds to date, use:

    import pandas
    result_ms=pandas.to_datetime('1493530261000',unit='ms')
    str(result_ms)
    
    Output: '2017-04-30 05:31:01'
    
  2. 10 digits(seconds) - To convert seconds to date, use:

    import pandas
    result_s=pandas.to_datetime('1493530261',unit='s')
    str(result_s)
    
    Output: '2017-04-30 05:31:01'
    
2018-03-07 13:14
by shubham


7

timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

Get the readable date from timestamp with time also, also you can change the format of the date.

2018-08-16 08:56
by Rishabh Jhalani
What does this answer add to this answer - Filip Kočica 2018-12-30 10:42


4

import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
2014-02-05 13:29
by itsaruns


2

i just successfully used:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date
2015-01-16 00:44
by nimmy
Thank you so much. This is exactly what I was looking for - Zargoon 2016-06-06 01:54


2

Another way that this can be done using gmtime and format function;

from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))

Output: 2018-10-4 11:57:44

2019-01-21 15:18
by h3xus


0

quick and dirty one liner:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

'2013-5-5-1-9-43'

2013-05-05 05:10
by eqzx
Or more concisely: '-'.join(map(str, datetime.datetime.now().timetuple()[:6]) - Jelle Zijlstra 2014-06-11 04:23
@JelleZijlstra Eh, I much prefer the generator expression over map - crhodes 2015-08-24 11:08
What kind of date format is '2013-5-5-1-9-43' ? I've never seen this format anywhere as a valid representation of a date/time - madoki 2016-02-09 18:18
can you elaborate on what qualifies this as an invalid representation @madoki ? do you mean nonstandard? The primary advantage it has over most other answers is the ability to include it in a file or directory path, as spaces and colons are not in the set of standard unix directory characters. see e.g. https://stackoverflow.com/a/458001/20924 - eqzx 2018-02-22 22:07


-1

You can use easy_date to make it easy:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")
2015-05-15 06:21
by Raphael Amoedo
Every programming has it's own date and time converters. One should never have to use mods/frameworks for thi - JosFabre 2015-12-09 14:55
strptime and strftime isn't intuitive... And even not readable... But I understand and respect your opinio - Raphael Amoedo 2015-12-09 18:06
That one should "never have to use" is wrong. It depends on the language and the quality of the built-in libs.

Javascript has moments.js and Java had Joda time which both are more popular than the respective built-in date and time conversion utils (so much that Joda time later influenced Java 8's updated standard libs).

That said, unless the question calls for nice third-party libraries, it's preferable to give an answer based on the standard library - Hejazzman 2015-12-22 23:57

I stand corrected @NikosVentouras. I've just had the "JS Date in IE behaves differently" issue for the first time. So I ended up using moment.j - JosFabre 2016-01-19 10:28


-2

There is an interesting way where you do not have to worry about the time zones, utc, etc. Simply convert the string into Excel date format, and then to a readable date/time:

import datetime

def xldate_to_datetime(xldate):
    temp = datetime.datetime(1899, 12, 30)
    delta = datetime.timedelta(days=xldate)
    return temp+delta

ts = "1284101485"
tsxl = ((int(ts)/60)/60)/24 + 25569
readabledate =  xldate_to_datetime(tsxl)
print(readabledate)
2018-04-27 23:10
by Gursel Karacor
Ads