Python3: Convert arbitrary date to day of the week - python

I am trying to convert dates of the following format:
2007-10-18 11:31:46 -0400 (Thu, 18 Oct 2007)
or
Thu, 18 Oct 2007 11:31:49 -0400
to the day of the week. Even though the day is given in the above dates, but how can I extract the only day of the week from the above dates?

Is this too simple:
days = {
'mon': 'Monday',
'thu': 'Thursday',
# and the others
}
haystack = '2007-10-18 11:31:46 -0400 (Thu, 18 Oct 2007)'
for acronym, full_name in days.items():
if acronym in haystack.lower():
print(f"Found {full_name}")

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
date = "2007-10-18 11:31:46 -0400 (Thu, 18 Oct 2007)"
for d in days:
if d in date:
print(d)

You can use dateutil.parser to get a datetime object from a string:
from dateutil import parser
dt = parser.parse("2007-10-18 11:31:46 -0400")
# dt = datetime.datetime(2007, 10, 18, 11, 31, 46, tzinfo=tzoffset(None, -14400))
Then just use datetime.weekday. This will give you a number from 0 to 6, where 0 is the first day of the week relatively to your timezone, Monday by default.
dt.weekday
# 3, starting from 0 so it's Thursday

Related

Best way to convert month int in month string + year

I'm trying to convert month int (1,2,...) into month string + year ("Jan 2020", "Feb 2020,...). So far, everything's going well. However, when I'm reaching 13, I would like to convert it to something like "Jan 2021"
Here is an example of what I'm trying to do (hard-coded)
I've tried to find the solution by myself but I think it's time to ask for help.
Is there a clean way to do it ? Thanks in advance !
You can use datetime module.
import datetime
def formated(year, month):
# datetime.date - class for date storing. It has useful method `strftime` for dates formating.
return datetime.date(year + (month - 1) // 12, (month - 1) % 12 + 1, 1).strftime("%b %Y")
print(formated(2020, 12))
# Dec 2020
print(formated(2020, 13))
# Jan 2021
print(formated(2020, 25))
# Jan 2022
import datetime
from dateutil import relativedelta
[datetime.datetime.strftime(datetime.date.today()+ relativedelta.relativedelta(months=i), "%b %Y") for i in range(13)]
Output:
['Feb 2021',
'Mar 2021',
'Apr 2021',
'May 2021',
'Jun 2021',
'Jul 2021',
'Aug 2021',
'Sep 2021',
'Oct 2021',
'Nov 2021',
'Dec 2021',
'Jan 2022',
'Feb 2022']
For the sake of simplicity I've taken datetime.date.today(). The dateutil module deals with months beyond 12
divmod can split a month into a year component (offset from 20200 and a month component. Since m == 1 should be January 2020, we'll subtract 1 from m, divide by 12, then add 1 back to the month. From this, we can create a datetime object whose strftime method can produce the desired string.
>>> from datetime import datetime
>>> m = 13 # Jan 2021
>>> year_offset, month = divmod(m-1, 12)
>>> datetime(2020 + year_offset, month + 1, 1).strftime("%b %Y")
'Jan 2021'
Note that the day argument doesn't really matter; it just has to be something valid for any month.
You can also add the "magic constant" 2019*12-1 to the month so that divmod returns the correct year immediately.
>>> m = 13 + 2019*12 - 1
>>> divmod(m, 12)
(2020, 0)
You still need to add one to the month.
Here is your solution:
month_names = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
number = int(input("Enter number: "))
if number != 0:
month = month_names[(number + 1) % 12]
year = number // 12 + 2020
print(month, year)
else:
print("Number can't be 0!")

Convert seconds to date and time in python

I have a DataFrame with a column containing seconds and I would like to convert the column to date and time and save the file with a column containing the date and time .I Have a column like this in seconds
time
2384798300
1500353475
7006557825
1239779541
1237529231
I was able to do it but by only inserting the number of seconds that i want to convert with the following code:
datetime.fromtimestamp(1238479969).strftime("%A, %B %d, %Y %I:%M:%S")
output : Tuesday, March 31, 2009 06:12:49'
What i want to get is the conversion of the whole column,I tried this :
datetime.fromtimestamp(df['time']).strftime("%A, %B %d, %Y %I:%M:%S") but I can not get it, any help of how i can do it will be appreciated.
Use df.apply:
In [200]: from datetime import datetime
In [203]: df['time'] = df['time'].apply(lambda x: datetime.fromtimestamp(x).strftime("%A, %B %d, %Y %I:%M:%S"))
In [204]: df
Out[204]:
time
0 Friday, July 28, 2045 01:28:20
1 Tuesday, July 18, 2017 10:21:15
2 Wednesday, January 11, 2192 03:33:45
3 Wednesday, April 15, 2009 12:42:21
4 Friday, March 20, 2009 11:37:11

Converting a string month day, year to mm/dd/yyyy

I need to covert a string which contains date information (e.g., November 3, 2020) into date format (i.e., 11/03/2020).
I wrote
df['Date']=pd.to_datetime(df['Date']).map(lambda x: x.strftime('%m/%d/%y'))
where Date is
November 3, 2020
June 26, 2002
July 02, 2010
and many other dates, but I found the error ValueError: NaTType does not support strftime.
You can use pandas.Series.dt.strftime, which handles the NaT:
import pandas as pd
dates = ['November 3, 2020',
'June 26, 2002',
'July 02, 2010',
'NaT']
dates = pd.to_datetime(dates)
df = pd.DataFrame(dates, columns=['Date'])
df['Date'] = df['Date'].dt.strftime('%m/%d/%y')
Output:
Date
0 11/03/20
1 06/26/02
2 07/02/10
3 NaN

Convert integer to dates in python

Is there aby way of converting integers of range(0,365) to dates (dtype='datetime64[D]')?
Eg:
0 -> 1 jan
1 -> 2 jan
.
.
31 -> 1 feb
.
.
364-> 31 dec
P.S: I don't need the year. Only date and month for a non-leap year.
As you have mentioned that you need the resultset for a non-leap year so create the datetime object with a non-leap year such as '2015'
from datetime import datetime, timedelta
for day_count in range(0, 365) :
curr_date_object = datetime.strptime('2015-01-01', '%Y-%m-%d') + timedelta(days=day_count)
print(curr_date_object.strftime("%d %b"))
This will return your desired result.
01 Jan
02 Jan
03 Jan
04 Jan
05 Jan
...
If you want the mapping to be in a dictionary, this is how it would look:
import datetime
In [35]: days = {}
In [36]: for i in range(0, 365):
...: days[i] = (datetime.datetime(2017, 1, 1) + datetime.timedelta(days=i)).strftime("%d %b")
...:
You'll get this:
In [37]: days
Out[37]:
{0: '01 Jan',
1: '02 Jan',
2: '03 Jan',
3: '04 Jan',
...

How can I convert the time in a datetime string from 24:00 to 00:00 in Python?

I have a lot of date strings like Mon, 16 Aug 2010 24:00:00 and some of them are in 00-23 hour format and some of them in 01-24 hour format. I want to get a list of date objects of them, but when I try to transform the example string into a date object, I have to transform it from Mon, 16 Aug 2010 24:00:00 to Tue, 17 Aug 2010 00:00:00. What is the easiest way?
import email.utils as eutils
import time
import datetime
ntuple=eutils.parsedate('Mon, 16 Aug 2010 24:00:00')
print(ntuple)
# (2010, 8, 16, 24, 0, 0, 0, 1, -1)
timestamp=time.mktime(ntuple)
print(timestamp)
# 1282017600.0
date=datetime.datetime.fromtimestamp(timestamp)
print(date)
# 2010-08-17 00:00:00
print(date.strftime('%a, %d %b %Y %H:%M:%S'))
# Tue, 17 Aug 2010 00:00:00
Since you say you have a lot of these to fix, you should define a function:
def standardize_date(date_str):
ntuple=eutils.parsedate(date_str)
timestamp=time.mktime(ntuple)
date=datetime.datetime.fromtimestamp(timestamp)
return date.strftime('%a, %d %b %Y %H:%M:%S')
print(standardize_date('Mon, 16 Aug 2010 24:00:00'))
# Tue, 17 Aug 2010 00:00:00

Categories

Resources