Pyhton3.10 datetime strftime and isocalendar disagreement - python

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

Related

Change '1 Apr 2022, noon' to datetime format python

I want to change '1 Apr 2022, noon' to YYYY-MM-DD HH:MM:SS format.
I know the datetime thing in python has the ability to parse but I am unsure how
You can use the dateparser module's parse() function:
>>> from dateparser import parse
>>> parse("1 Apr 2022, noon")
datetime.datetime(2022, 4, 1, 12, 0)
This gets us a datetime.datetime object. We can now call strftime() to format it properly:
>>> date_time = parse("1 Apr 2022, noon")
>>> print(date_time.strftime("%Y-%m-%d %H:%M:%S")
'2022-04-01 12:00:00'

How to convert epoch time to time

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'))

Python: datetime format

I have the following datetime string:
Mon Oct 27 23:00:03 +0000 2014
I would like to convert this string to a form where I could compare the datetimes. So, the first thing I tried is converting this to a datetime in Python.
I am having trouble with the correct formatting. I have followed the documentation, but it does not work.
I have tried the following:
str = 'Mon Oct 27 23:00:03 +0000 2014'
datetime.strptime(str, '%a %b %d %X %Z %Y')
How can I get this to work?
If you want to convert it to the datetime object you can use library python-dateutil.
For example:
In [6]: dateutil.parser.parse('Mon Oct 27 23:00:03 +0000 2014')
Out[6]: datetime.datetime(2014, 10, 27, 23, 0, 3, tzinfo=tzutc())
In Python 3.2+:
>>> from datetime import datetime
>>> timestr = 'Mon Oct 27 23:00:03 +0000 2014'
>>> datetime.strptime(timestr, '%a %b %d %X %z %Y')
datetime.datetime(2014, 10, 27, 23, 0, 3, tzinfo=datetime.timezone.utc)
Note the lower case %z.
Here's a stdlib-only version that works on Python 2 and 3:
#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
timestamp = mktime_tz(parsedate_tz('Mon Oct 27 23:00:03 +0000 2014'))
utc_dt = datetime.utcfromtimestamp(timestamp)
# -> datetime.datetime(2014, 10, 27, 23, 0, 3)
where utc_dt is a datetime object that represents time in UTC timezone (regardless of the input timezone).
Note: it doesn't support the time that represents a leap second (though datetime object can't represent it anyway):
>>> datetime.utcfromtimestamp(mktime_tz(parsedate_tz('Tue June 30 23:59:60 +0000 2015')))
datetime.datetime(2015, 7, 1, 0, 0)
Your problem lies with your %z UTC offset value (you should've used a lowercase z). However,
%z is only supported in Python 3.2+
If you are stuck with an older version of Python, you could possibly take out the UTC offset from the string and try converting it after you convert the rest

Convert timestamp since epoch to datetime.datetime

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

Format date with month name in polish, in python

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")

Categories