I have the following timestamps since epoch:
Timestamp
1346114717972
1354087827000
How can I convert these timestamps to some specific output format, e.g., mm/dd/yyyy hr:min:sec?
I have tried to convert them to datetime.datetime but it failed:
>>> datetime.datetime.fromtimestamp(1346114717972)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: timestamp out of range for platform time_t
How can I do this?
I would use the time module
>>> import time
>>> time.gmtime(1346114717972/1000.)
time.struct_time(tm_year=2012, tm_mon=8, tm_mday=28, tm_hour=0, tm_min=45, tm_sec=17, tm_wday=1, tm_yday=241, tm_isdst=0)
This shows the timestamp in UTC/GMT time.
The timestamp is divided by 1000 as the stamps you have provided are in milliseconds since the epoch, not seconds.
Then use strftime to format like so:
>>> time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(1346114717972/1000.))
'08/28/2012 00:45:17'
Assuming millisecond resolution:
import datetime
s = '1346114717972'
fmt = "%Y-%m-%d %H:%M:%S"
# local time
t = datetime.datetime.fromtimestamp(float(s)/1000.)
print t.strftime(fmt) # prints 2012-08-28 02:45:17
# utc time
t_utc = datetime.datetime.utcfromtimestamp(float(s)/1000.)
print t_utc.strftime(fmt) # prints 2012-08-28 00:45:17
Have a look at the documentation for the strftime() and strptime() behavior.
This is the simplest method I've ever seen-
$ python
Python 2.7.5 (default, Nov 6 2016, 00:28:07)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> print(time.strftime('%Y-%m-%dT%H:%M:%S %Z',time.localtime(time.time())))
2018-05-02T13:21:44 IST
Related
I believe that strftime is wrong in the example below. The year should be 2021. isocalendar is right.
Python 3.10.0 (v3.10.0:b494f5935c, Oct 4 2021, 14:59:20) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin
>>> import datetime
>>> datetime.date( 2022, 1, 1 ).strftime( '%Y-%V' )
'2022-52'
>>> datetime.date( 2022, 1, 1 ).isocalendar()
datetime.IsoCalendarDate(year=2021, week=52, weekday=6)
Actually this is the expected behaviour since you are using the %Y format specifier which will return the actual year of the date object.
However you want to use the %G format specifier to return the corresponding ISO year of the date, so try:
import datetime
datetime.date(2022, 1, 1).strftime('%G-%V')
# '2021-52'
Find out more from the docs: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
I have epoch time like this 1488445200000
and I need to convert it to datetime variable. I tried
from datetime import datetime
dt = datetime.fromtimestamp(1488445200000 // 3600)
dt
I got
datetime.datetime(1983, 2, 7, 10, 10)
but the result does not seem to be right (the right one should be March 2, 2017 10:00:00 AM GMT+01:00)... what shall I do?
And what if what is I need to do is not just for one value 1488445200000 but for a column in a dataframe. Do I have to loop? Or is there a matrix operation?
Your timestamp is in milliseconds and datetime expects seconds. Divide by 1000 and it works:
$ python3
Python 3.7.0 (default, Jun 29 2018, 20:13:13)
[Clang 9.1.0 (clang-902.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> dt = datetime.fromtimestamp(1488445200000 // 1000)
>>> dt
datetime.datetime(2017, 3, 2, 10, 0)
Try This:
Use datetime module:
from datetime import datetime
ts = int(1488445200000//1000)
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
Based on this code, how do I get the UTC offset of a given date by seconds. Get UTC offset from time zone name in python
Currently, I have this code:
Python 2.7.3 (default, Jul 3 2012, 19:58:39)
[GCC 4.7.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pytz
>>> import datetime
>>> offset = datetime.datetime.now(pytz.timezone('US/Pacific')).strftime('%z')
>>> offset
'-0700'
>>> int(offset)*3600
-2520000
>>> int(offset)*360
-252000
>>>
For example, US/Pacific sometimes is -800 hours (probably military time :D) but I need it to be in seconds, ex: -25200.
Shall I just multiply it by 360? Doesn't sound right but who knows.
TIA
>>> import datetime, pytz
>>> melbourne = pytz.timezone("Australia/Melbourne")
>>> melbourne.utcoffset(datetime.datetime.now())
datetime.timedelta(0, 36000)
>>> pacific = pytz.timezone("US/Pacific")
>>> pacific.utcoffset(datetime.datetime.now())
datetime.timedelta(-1, 61200)
>>> -1*86400+61200
-25200
>>> pacific.utcoffset(datetime.datetime.now()).total_seconds()
-25200.0
Is there an out of the box way to format in python (or within django templates), a date with full month name in accordance to polish language rules?
I want to get:
6 września 2010
and not:
>>> datetime.today().date().strftime("%d %B %Y")
'06 wrzesień 2010'
Use Babel:
>>> import babel.dates
>>> import datetime
>>> now = datetime.datetime.now()
>>> print(babel.dates.format_date(now, 'd MMMM yyyy', locale='pl_PL'))
6 września 2010
Update: Incorporated Nathan Davis' comment.
https://docs.djangoproject.com/en/stable/ref/templates/builtins/#date
E
Month, locale specific alternative representation usually used for long date representation.
'listopada' (for Polish locale, as opposed to 'Listopad')
If you want to specify format in your html template then this will do:
{{ datefield|date:"j E Y" }}
OP's code now works as he intended: returning '30 kwietnia 2020' and not 30 kwiecień 2020. Tested today with Python 2.7 and Python 3.6. Setting locale was required, I used the platform one - this might be an issue with web-apps as per other answers.
$ python
Python 2.7.17 (default, Apr 15 2020, 17:20:14)
[GCC 7.5.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> [cut repeated code]
$ python3.6
Python 3.6.9 (default, Apr 18 2020, 01:56:04)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2020, 4, 30, 18, 13, 21, 308217)
>>> datetime.datetime.today().strftime("%d %B %Y")
'30 April 2020'
>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'pl_PL.UTF-8'
>>> datetime.datetime.today().strftime("%d %B %Y")
'30 kwietnia 2020'
Try this...
datetime.today().date().strftime("%-d %B %Y")
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
Yes, at least on Windows (using Windows 7 here). What platform are you using?
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
>>> time.gmtime(1000*365*24*60*60)
time.struct_time(tm_year=2969, tm_mon=5, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=123, tm_isdst=0)
Also, even on Linux you should be able to do some processing of dates well beyond 2038 using the datetime module. The docs say MAXYEAR is 9999 for that module:
>>> dt = datetime.datetime.now().replace(year=1000+1971)
>>> dt
datetime.datetime(2971, 12, 29, 11, 43, 20, 727000)
>>> dt.timetuple()
time.struct_time(tm_year=2971, tm_mon=12, tm_mday=29, tm_hour=11, tm_min=41, tm_sec=16, tm_wday=6, tm_yday=363, tm_isdst=-1)
Of course, that last call probably won't work on Linux if the time.gmtime() call is failing, but since you haven't really said what you want to do with the date maybe this is sufficient for now.