How to convert date to datetime in python - python

Code:
def func(y, m):
for i in range(1, calendar.monthrange(y, m)[1]+1):
th_date = date(y, m, i)
print(th_date)
func(2020,4)
Note:
i am getting dates as date format i want to convert it into datetime i don't want time

You might just use datetime in place of date as 4th and following arguments to datetime.datetime are optional, so
import datetime
dt = datetime.datetime(2022,6,2)
print(dt)
gives output
2022-06-02 00:00:00

If you're not interested in time but you want to use the datetime module then you can use the date class. For example:
from datetime import date
def func(year, month, day=1):
return date(year, month, day)
print(func(2022, 4))
Output:
2022-04-01

Related

extract date, month and year from string in python

I have this column where the string has date, month, year and also time information. I need to take the date, month and year only.
There is no space in the string.
The string is on this format:
date
Tuesday,August22022-03:30PMWIB
Monday,July252022-09:33PMWIB
Friday,January82022-09:33PMWIB
and I expect to get:
date
2022-08-02
2022-07-25
2022-01-08
How can I get the date, month and year only and change the format into yyyy-mm-dd in python?
thanks in advance
Use strptime from datetime library
var = "Tuesday,August22022-03:30PMWIB"
date = var.split('-')[0]
formatted_date = datetime.strptime(date, "%A,%B%d%Y")
print(formatted_date.date()) #this will get your output
Output:
2022-08-02
You can use the standard datetime library
from datetime import datetime
dates = [
"Tuesday,August22022-03:30PMWIB",
"Monday,July252022-09:33PMWIB",
"Friday,January82022-09:33PMWIB"
]
for text in dates:
text = text.split(",")[1].split("-")[0]
dt = datetime.strptime(text, '%B%d%Y')
print(dt.strftime("%Y-%m-%d"))
An alternative/shorter way would be like this (if you want the other date parts):
for text in dates:
dt = datetime.strptime(text[:-3], '%A,%B%d%Y-%I:%M%p')
print(dt.strftime("%Y-%m-%d"))
The timezone part is tricky and works only for UTC, GMT and local.
You can read more about the format codes here.
strptime() only accepts certain values for %Z:
any value in time.tzname for your machine’s locale
the hard-coded values UTC and GMT
You can convert to datetime object then get string back.
from datetime import datetime
datetime_object = datetime.strptime('Tuesday,August22022-03:30PM', '%A,%B%d%Y-%I:%M%p')
s = datetime_object.strftime("%Y-%m-%d")
print(s)
You can use the datetime library to parse the date and print it in your format. In your examples the day might not be zero padded so I added that and then parsed the date.
import datetime
date = 'Tuesday,August22022-03:30PMWIB'
date = date.split('-')[0]
if not date[-6].isnumeric():
date = date[:-5] + "0" + date[-5:]
newdate = datetime.datetime.strptime(date, '%A,%B%d%Y').strftime('%Y-%m-%d')
print(newdate)
# prints 2022-08-02

How to convert a date string zone oriented and hour string into datetime

I have two strings one: date='2021-12-30T23:00Z' where Z means UTC timezone and 23:00 means hour. I also have an hour string hour='3'. What I want is to convert date to datetime object and add this hour string to date as a delta. In result I would get a datetime object with hour: '2021-12-31T02:00Z' I tried function datetime.datetime.fromisoformat() with no luck.
Use strftime with their format.
from datetime import datetime, timedelta
date='2021-12-30T23:00Z'
date = datetime.strptime(date, '%Y-%m-%dT%H:%MZ')
new_date = date + timedelta(hours=3)
new_date = new_date.strftime('%Y-%m-%dT%H:%MZ')
print(new_date)
Output:
2021-12-31T02:00Z
You could do something like this:
from datetime import datetime
from datetime import timedelta
date = "2021-12-30T23:00Z"
hour = "3"
d = datetime.strptime(date, "%Y-%m-%dT%H:%M%z") + timedelta(hours=int(hour))
print(d)
output:
2021-12-31 02:00:00+00:00

How to convert a 'day/month' string to date in python and compare it with an Odoo date field?

I have a day/month string, I want to convert that string to date object and compare the last day of that month to another date
Example:
For 08/2021 (august, 2021) I want to compare the last day of that month (31-08-2021) to another date (date field),
For 02/2020 I what to compare 29-02-2020 < another_date (date field)
For 02/2021 I what to compare 28-02-2020 < another_date (date field)
You can use calendar.monthrange to find the last day in the month if you don't want to add dateutil.
import calendar
from datetime import datetime
def get_last_day_date(year_month_str):
date = datetime.strptime(year_month_str, "%m/%Y")
last_day = calendar.monthrange(date.year, date.month)[1]
return datetime(date.year, date.month, last_day)
get_last_day_date("08/2020")
# datetime.datetime(2020, 8, 31, 0, 0)
This examples shows you how to convert '02/2020' to a Python datetime and how to get the last day of that month. You can use it to compare the result to another datetime:
import datetime
from dateutil.relativedelta import relativedelta
date = '02/2020'
last_day = datetime.datetime.strptime(date, '%m/%Y') + relativedelta(day=31)
# last_day will be a datetime of the last day of the month which you can use to compare against another datetime
In this example, the result is datetime.datetime(2020, 2, 29, 0, 0) because 2020 was a leap year
b='08/2021'
a=b.split('/')
import calendar
import datetime
z=(str(calendar.monthrange(int(a[1]),int(a[0]))[1])+'-'+b.replace('/','-'))
d=datetime.datetime.strptime(z,'%d-%m-%Y').date()
print(d)
n=datetime.date.today()
print(n)
n<d
Output:
2021-08-31
2021-01-28
True
It can be done by just importing/using datetime library and here you can see how.
By passing string date into method.
import datetime
def convert_string_to_datetime(self, datetime_in_string):
datetime_in_string = str(datetime_in_string)
datetime_format = "%Y-%m-%d %H:%M:%S"
datetime_in_datetime_format = datetime.datetime.strptime(datetime_in_string, datetime_format)
return datetime_in_datetime_format
new_datetime_field = convert_string_to_datetime(datetime_in_string)
By modifying with in single line
import datetime
new_datetime_field = datetime.datetime.strptime(YOUR_DATETIME_IN_STRING, "%Y-%m-%d %H:%M:%S")
After converting into datetime now comparison is possible like.
if new_datetime_field > odoo_datetime_field:
pass

Unable to subtract a day from any specific date format

I'm trying to subtract a day from this date 06-30-2019 in order to make it 06-29-2019 but can't figure out any way to achive that.
I've tried with:
import datetime
date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')
print(date)
It surely gives me back the date I used above.
How can I subtract a day from a date in the above format?
try this
import datetime
date = "06/30/19"
date = datetime.datetime.strptime(date, "%m/%d/%y")
NewDate = date + datetime.timedelta(days=-1)
print(NewDate) # 2019-06-29 00:00:00
Your code:
date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')
Check type of date variable.
type(date)
Out[]: str
It is in string format. To perform subtraction operation you must convert it into date format first. You can use pd.to_datetime()
# Import packages
import pandas as pd
from datetime import timedelta
# input date
date = "06-30-2019"
# Convert it into pd.to_datetime format
date = pd.to_datetime(date)
print(date)
# Substracting days
number_of_days = 1
new_date = date - timedelta(number_of_days)
print(new_date)
output:
2019-06-29 00:00:00
If you want to get rid of timestamp you can use:
str(new_date.date())
Out[]: '2019-06-29'
use timedelta
import datetime
date = datetime.datetime.strptime("06/30/19" ,"%m/%d/%y")
print( date - datetime.timedelta(days=1))

python datetime swapping day month

I have a date time object that looks like:
2015-31-12 00:34:00
where the second element (31) represents the day and the third element (12) represents the month. How do I swap day and month so that the date looks like:
2015-12-31 00:34:00
You'd parse the string into a datetime object then format it again back to a string:
from datetime import datetime
result = datetime.strptime(inputstring, '%Y-%d-%m %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
Demo:
>>> from datetime import datetime
>>> inputstring = '2015-31-12 00:34:00'
>>> datetime.strptime(inputstring, '%Y-%d-%m %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
'2015-12-31 00:34:00'
So the datetime.strptime() parses the string given a pattern, where you specify that the order is year-day-month, and datetime.strftime() formats it back to a string, with the day and month positions swapped.
Use .strftime('%Y-%m-%d %H:%M:%S').
For example:
from datetime import datetime
formatted_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')

Categories

Resources