Date and Time Python (Stuck) - python

I am Python beginner. I have a question about Date and time code:
import datetime
date = datetime.date.today()
print(date.strftime('date is %d%b,%Y'))
Now I want to print the date of my own choice. How can I do it?
For example, if today's date is (15 sep 2016) and I want to print (23 oct 1998), what should I do in order to make it work?

You may do it like so:
>>> from datetime import date
>>> date(year=1998, month=10, day=23)
datetime.date(1998, 10, 23)
>>> _.strftime('date is %d %b,%Y')
'date is 23 Oct,1998'
As per datetime.date() documentation, date() accepts a year, month and a day.

You can initialize date using datetime constructor.
>>>import datetime
>>>d = datetime.datetime(1998,10,23)
>>>print(d.strftime('date is %d %b,%Y'))

If you needed to take a string value as input you can use
from dateutil import parser
datestring = "23 Oct 1998"
customDate = parser.parse(datestring)
print(customDate.strftime('date is %d%b,%y'))

Related

Getting the Current year, month and date on python script

I am trying to get only the year output from the below script, but when I check for the same I am getting
/year=2020-08-20 19:11:26.616679/month=2020-08-20 19:11:26.616689/date=2020-08-20 19:11:26.616690'
Is there a way to get in year=2020, month=08, and date=20 format?
year = datetime.datetime.now()
from datetime import date
print(date.today().strftime('%Y, %m, %d'))
With datetime module, you can have something like this
from datetime import datetime
year = datetime.now()
print(datetime.strftime(year, 'year=%Y, month=%m, date=%d'))

How to compare date in python? I have a month date year format and want to compare to the current date (within 7 days)

This is the data that is being returned from my API:
"Jun 02, 2021, 2 PMEST"
If I'm within 7 days of the current date which I'm getting by doing this:
from datetime import date
today = date.today()
print("Today's date:", today)
Just need to convert Jun to a number and 02 and compare to see if it's within 7 days in the future of the current date, then return True
APPROACH 0:
Given the format of your example data, you should be able to convert it to a datetime using this code:
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
The details about this format string are here: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
However, when I tested this locally, it worked for this input:
"Jun 02, 2021, 2 PMUTC"
but not for your input (which has different timezone):
"Jun 02, 2021, 2 PMEST"
I have investigated this some more and "read the docs" (https://docs.python.org/3/library/time.html).
To get EST parsing to work, you would have to change your OS timezone and reset the time module's timezones like this:
from datetime import datetime
import os
import time
os.environ["TZ"] = "US/Eastern". # change timezone
time.tzset(). # reset time.tzname tuple
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
When you're done, be safe and delete the "hacked" environment variable:
del os.environ["TZ"]
Note - Since your system timezone is presumably still UTC, it can still parse UTC timezone too.
See this thread for detailed discussion: https://bugs.python.org/issue22377
Also note that the timestamp is not actually captured. The result you get with EST and UTC is a naive datetime object.
APPROACH 1
So, it seems like there is a better way to approach this.
First, you need to pip install dateutils if you don't already have it.
THen do something like this:
from dateutil import parser
from dateutil.tz import gettz
tzinfos = {"EST": gettz("US/Eastern")}
my_datetime = parser.parse("Jun 02, 2021, 2 PM EST", tzinfos=tzinfos)
What's happening here is we use gettz to get timezone information from the timezones listed in usr/share/zoneinfo. Then the parse function can (fuzzy) parse your string (no format needs to be specified!) and returns my_datetime which has timezone information on it. Here are the parser docs: https://dateutil.readthedocs.io/en/stable/parser.html
I don't know how many different timezones you need to deal with so the rest is up to you. Good luck.
Convert the date to a datetime structure and take the direct difference. Note that today must be a datetime, too.
import datetime
date_string = "Jun 02, 2021, 2 PMEST"
today = datetime.datetime.today()
date = datetime.datetime.strptime(date_string,
"%b %d, %Y, %I %p%Z") # Corrected
(date - today).days
#340

Converting python time stamp to day of year

How can I convert a python timestamp into day of year:
Timestamp('2015-06-01 00:00:00')
I want a number where Jan 1 is 1, Jan 2 is 2... Dec 31 is 365 (for a non-leap year)
You might want to take a look at the function datetime.timetuple() which returns a time.struct_time object with your desired attribute. It has a named tuple interface, so you can access the values by index or attribute name.
import datetime
date = datetime.datetime.strptime("2015-06-01 00:00:00",
"%Y-%m-%d %H:%M:%S")
print date.timetuple().tm_yday
#=> 152
First, you can convert it to a datetime.datetime object like this:
>>> import datetime
>>> format = "%Y-%m-%d %H:%M:%S"
>>> s = "2015-06-01 00:00:00"
>>> dt = datetime.datetime.strptime(s, format)
Now you can use the methods on dt to get what you want,except that dt doesn't have the function you want directly, so you need to convert to a time tuple
>>> tt = dt.timetuple()
>>> tt.tm_yday
152

Convert a particular timestamp with Python 2.7.x

I have a timestamp like:
2014-01-01T05:00:00.000Z
How do I convert this so that I can easily get the month like "January"? And in general convert it to a nice format like:
January 1st, 2014
You can use datetime module. datetime.datetime expects a time string and its formatting and returns a datetime.datetime object, on which you can call strftime() to format it according to your needs.
>>> import datetime
>>> my_date = datetime.datetime.strptime("2014-01-01T05:00:00.000Z", "%Y-%m-%dT%H:%M:%S.%fZ")
>>> my_date.strftime('%d.%m.%Y')
01.01.2014
>>> date.strftime('%H:%M:%S %d.%m.%Y')
'05:00:00 01.01.2014'
There is also a python-dateutils module, which can do the same.
The strftime() method in datetime modulecan achieve this. It expects a string pattern explaining how you want to format your date.
import datetime
today = datetime.date.today()
print today.strftime('It is %d %b %Y')
The above code prints something like "It is 12 Nov 2015"
You can find more format codes at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

Python: How can I see if a given month and day have already passed this year?

Today it's 16 Feb. I have a string 23 Mar. How can I check if my string is before or after the current day?
I have a list of files with the last modified date attached. They only have a day and month, no year. If the date has already passed this year (e.g. 16/01), the year should be 2014, if not (e.g. 30/12), the year should be 2013.
Parse out the string into a datetime object using datetime.datetime.strptime(), but since your date string has no year attached to it, do attach the current year to it:
import datetime
today = datetime.date.today()
yourdate = datetime.datetime.strptime(inputstring, '%d %b')
yourdate = yourdate.date().replace(year=today.year)
if yourdate >= today:
# date not before today, attach *last* year
yourdate = yourdate.replace(year=today.year - 1)
I converted the datetime object to a date object here too since we only need to talk about dates.
This does assume your date strings always are of the form day-of-the-month month-abbreviated in English.
Demo:
>>> import datetime
>>> inputstring = '23 Mar'
>>> today = datetime.date.today()
>>> yourdate = datetime.datetime.strptime(inputstring, '%d %b')
>>> yourdate = yourdate.date().replace(year=today.year)
>>> yourdate
datetime.date(2014, 3, 23)
>>> yourdate >= today
True

Categories

Resources