Day of week constants with Sunday = 0 in Python - python

The calendar module has day of week constants beginning with
calendar.MONDAY
Out[60]: 0
However, sometimes one must interface with a system (perhaps written in JavaScript) that uses the convention Sunday = 0. Does Python provide such constants?

There are no such constants in the Python standard library. It is trivial to define your own however:
SUN, MON, TUE, WED, THU, FRI, SAT = range(7)
or, when using Python 3.4 or up, you could use the enum module functional API:
from enum import IntEnum
Weekdays = IntEnum('Weekdays', 'sun mon tue wed thu fri sat', start=0)
weekday == Weekdays.wed
and then you can then also map a weekday integer to an enumeration value by calling the enum.Enum object:
weekday_enum = Weekdays(weekday)
I used 3-letter abbreviations but you are free to use full names if you find that more readable.

I just use this with mydate.isoweekday(), does the job.
def weekday_sun_zero(self, isoweekday):
return 0 if isoweekday == 7 else isoweekday

hope this helps:
from datetime import datetime
weekdays_dic ={0:'Mon', 1:'Tue',2:'Wed',3:'Thu',4:'Fri',5:'Sat', 6:'SUN'}
print(weekdays_dic[datetime.today().weekday()])

Related

Is there a Python datetime library function that does the same thing as Oracle's NEXT_DAY function?

Oracle has a very useful function for finding the date of the next weekday. This function is called NEXT_DAY. It takes a start date, say 15-OCT-2009, and the weekday we're expecting, say TUESDAY. The result of NEXT_DAY('15-OCT-2009', 'TUESDAY') is 20-OCT-2009 because that's the next Tuesday after the 15th of October 2009.
Does Python have a function, be it Built-in or via the datetime library, that does this same thing?
I need it to deterministically return true/false for the question "if this day was in November, is it Thanksgiving?" without referencing any kind of lookup table for any year.
It's used by looking at the day number, the 15th part from above, and finding the number of days until the next Thursday in October then adding 21 to that. An alternative method of answering the question "is the day Thanksgiving?", deterministically, at runtime, without any lookup tables, restricted to plain Python or the datetime library would work for my situation but would not work to answer the question in the title.
I think this should work.
from datetime import datetime,timedelta
def next_day(date, day_of_week):
if date.weekday() == day_of_week:
return (date + timedelta(days=7)).date()
else:
return (date + timedelta(days=(day_of_week - date.weekday() + 7) % 7)).date()
# Test
day_names = "mon tue wed thu fri sat sun".split()
now = datetime.now()
print(f"Today is {day_names[now.weekday()]}, {now.date()}")
for i in range(7):
print(f"next {day_names[i]}: {next_day(now, i)}")
Ouput
Today is thu, 2023-02-16
next mon: 2023-02-20
next tue: 2023-02-21
next wed: 2023-02-22
next thu: 2023-02-23
next fri: 2023-02-17
next sat: 2023-02-18
next sun: 2023-02-19
Have a look at Delorean (need to install via pip) and it's natural language capabilities
e.g. finding Thanksgiving for given year
import delorean as dl
from datetime import datetime
year = int(input('Enter a year:'))
d = dl.Delorean(datetime(year,11,30), timezone='UTC')
print(f"In {year} Thanksgiving is {d.last_thursday().date}")
output
Enter a year:2023
In 2023 Thanksgiving is on 2023-11-23
Enter a year:2022
In 2022 Thanksgiving is 2022-11-24
or finding next Monday
print(dl.Delorean(datetime.now(), timezone='utc').next_monday().date)
output
2023-02-20

How to convert a date into a time period python

User case:
June 2016(OR 06/2016) => 06/01/2016-06/30/216
June 2016 to Dec 2016(OR between June 2016 and Dec 2016) => 06/01/2016-12/31/216
I'm wondering if there a python library or API service I can call from python, so that I can translate date in a natural language into a standard time period like the above user case
Looks like dateutil should help.
Ex:
from dateutil import parser
from dateutil.relativedelta import relativedelta
s = 'June 2016(OR 06/2016)'
s = s.split("(OR")
start = parser.parse(s[0]).strftime("%m/01/%Y")
end = (parser.parse(start) + relativedelta(day=31)).strftime("%m/%d/%Y")
print "{0}-{1}".format(start, end)
Output:
06/01/2016-06/30/2016

How to handle "/Date(1262476800000)/" [duplicate]

This question already has answers here:
Convert weird Python date format to readable date
(2 answers)
Closed 7 years ago.
Recently I received this output from an API (I think it's .NET driven).. What kind of date format is this and how do I convert it to a Python date object?
{
Id: 10900001,
ExpirationDate: "/Date(1262476800000)/",
}
It seems a timestamp but I get parse errors on fromtimestamp()
>>> from datetime import datetime
>>> datetime.fromtimestamp(float('1262476800000'))
ValueError: 'year is out of range'
You are getting the error because the timestamp is in milliseconds. You just remove the last 3 digits and it will work -
>>> from datetime import datetime, timedelta
>>> s = '1262476800540'
>>> d = datetime.fromtimestamp(float(s[:-3]))
>>> d = d + timedelta(milliseconds=int(s[-3:]))
>>> print d
2010-01-03 05:30:00.540000
>>> from datetime import datetime
>>> a = datetime.fromtimestamp(float('1262476800002')/1000)
>>> a.microsecond
2000
As it seems the API's output is JSON, I would assume it is a javascript timestamp. To convert it to python, remove the milliseconds and you should be fine.
From an online conversion tool http://www.epochconverter.com/
GMT: Sun, 03 Jan 2010 00:00:00 GMT
It seems like a UNIX time stamp in milliseconds. In other words 1262476800(000) = 2010-01-03T00:00:00+00:00
Could that be correct?
You can use fromtimestamp to convert it to a date object.
Cheers,
Anders
Also you can use time module.
In [13]: import time
In [14]: time.ctime(1262476800000)
Out[14]: 'Mon Apr 19 02:00:00 41976\n'
I think you'll have to peruse the documentation of that API. Failing which, can you reverse-engineer it? If you can create entities in that system, then do so. If you create 3 entities expiring on 1st Jan 2016, 11th Jan 2016 and 21st Jan 2016, you'll be able to see if it's (probably) a linearly increasing sequence of time-units and deduce what are the units and the base-date. Even if you can't create entities, can you get the dates in human-readable format through a human-orientated web interface?
Once you know what the number represents, you can decode it either into year, month, day ... fields, or into a number of seconds since the canonical base date (timestamp).
Or maybe you'll get lucky and another reader will recognise the format!

Parsing a String date into a date object in Python

I am parsing a log file and one element contains the date as a String:
Tue Mar 31 20:24:23 BST 2015
The date is in element[i][0] of a 2DList
What I am a little stumped on (without going about this in some awful compare and replace manner) is how to turn this date into something comparable in Python.
I get a few entries in a log file which are within a few minutes of each other, so I would like to group these as one.
Tue Mar 31 20:24:23 BST 2015
Tue Mar 31 20:25:45 BST 2015
Tue Mar 31 20:26:02 BST 2015
What options can be suggested?
I am aware that I can input logic to replace 'Mar' with 3, remove Day Tue/Wed etc strings, but everything else is somewhat needed.
Would it be acceptable to replace a : with / I can then split the date into a list by its ' ' delimiter, then compare the 20/26/02 element, but before I go and do all that, is there a built in way? I have searched and found python datetime 1, which I would use after a lot of replacing values.
Really, I'm looking for a built in method!
You can use the datetime.datetime.strptime.
Here are format specifiers.
Something like datetime.strptime(your_string, "%a %b %d %H:%M:%S %Z %Y") should do the work.

Parse date/time from a string

I'm using Python 3.3. I'm getting an email from an IMAP server, then converting it to an instance of an email from the standard email library.
I do this:
message.get("date")
Which gives me this for example:
Wed, 23 Jan 2011 12:03:11 -0700
I want to convert this to something I can put into time.strftime() so I can format it nicely. I want the result in local time, not UTC.
There are so many functions, deprecated approaches and side cases, not sure what is the modern route to take?
Something like this?
>>> import time
>>> s = "Wed, 23 Jan 2011 12:03:11 -0700"
>>> newtime = time.strptime(s, '%a, %d %b %Y %H:%M:%S -0700')
>>> print(time.strftime('Two years ago was %Y', newtime))
Two years ago was 2011 # Or whatever output you wish to receive.
I use python-dateutil for parsing datetime strings. Function parse from this library is very handy for this kind of task
Do this:
import email, email.utils, datetime, time
def dtFormat(s):
dt = email.utils.parsedate_tz(s)
dt = email.utils.mktime_tz(dt)
dt = datetime.datetime.fromtimestamp(dt)
dt = dt.timetuple()
return dt
then this:
s = message.get("date") # e.g. "Wed, 23 Jan 2011 12:03:11 -0700"
print(time.strftime("%Y-%m-%d-%H-%M-%S", dtFormat(s)))
gives this:
2011-01-23-21-03-11

Categories

Resources