Grabbing & displaying the current time - python

I'm very new to python and trying to build a simple web app in pieces.
I'm using the datetime library for the first time so please be patient with me.
All I'm trying to do is to get and display the current time and date so that I can cross-reference it with a target time & date later.
I'm getting some colossal errors. Any help is appreciated. Not sure what I'm doing incorrectly here to display the time formatted the way I want.
from datetime import datetime
date_string = "4:21 PM 1.24.2011"
format = "%I.%M %p %m %d, %Y"
my_date = datetime.strptime(date_string, format)
print(my_date.strftime(format))

The format of the date_string doesn't match the format you're trying to parse it with. The following format string should allow you to parse the date.
format = "%I:%M %p %m.%d.%Y"
And afterwards, if you want to print it using the other format
print(my_date.strftime("%I.%M %p %m %d, %Y"))

You're using wrong format string. Try to replace it with "%I:%M %p %m.%d.%Y".
Here's documentation how to use datetime class properly.

The problem is with your format. You need to make the format match date_string. So try this:
format = "%I:%M %p %m.%d.%Y"
That should do the trick
Also, it might be of interest to you to take a look at time.asctime

Related

Correct reading of datetime with AM/PM format

I'm trying to read some csv files that contain a column called 'timestamp' with this format:
7/6/2022 7:30:00 PM which should translate to (mm/dd/YYYY hh:mm:ss). What I tried was after reading the csv file using:
df['timestamp']= pd.to_datetime(df['timestamp'],format='%m/%d/%Y %I:%M:%S %p')
And it renders a totally different thing with this error:
ValueError: time data '07-06 19:30' does not match format '%m/%d/%Y %I:%M:%S %p' (match)
'07-06 19:30' This value is the same that appears when reading the csv directly with no formatting which is strange as when I open the csv the full date is there. I'm a bit lost on this case as it appears as I cannot convert the date.
Thanks
The format='%m/%d/%Y %I:%M:%S %p' should work, make sure you read your data as string.
That said, pandas is advanced enough to figure out the format semi-automatically, the only ambiguity to resolve is to specify that the first digits are not days:
df['new_timestamp'] = pd.to_datetime(df['timestamp'], dayfirst=False)
example:
timestamp new_timestamp
0 7/6/2022 7:30:00 PM 2022-07-06 19:30:00

What is the proper format for code for this datetime.strptime function?

I have a python program that ingests and processes data, yet one field is not converting properly. One piece of data comes in as a string of java.time.OffsetDateTime.now(ZoneOffset.UTC) and we use strptime to create a datetime object. Here is the simplified code:
$ python
from datetime import datetime
# source string format: (java.time.OffsetDateTime.now(ZoneOffset.UTC))
date_string = "2021-06-28T19:47:27.510670082Z"
# this works yet is not in the source format
date_string = "2021-06-28T19:47:27.510670"
datetime_object = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f')
print (datetime_object)
Results in this error
ValueError: unconverted data remains: 082Z
What is the proper format code to create the datetime object?
Just use dateutil. You have time in ISO 8601 format with setting of timezone
from dateutil import parser
# source string format: (java.time.OffsetDateTime.now(ZoneOffset.UTC))
date_string = "2021-06-28T19:47:27.510670082Z"
datetime_object = parser.parse(date_string)
print(datetime_object) # 2021-06-28 19:47:27.510670+00:00

Python convert string to datetime in variable formats

I am generating date and time information which is string from an API. The generated string is in your system's date/time format by default (Win 10 in my case). For example if you are using MM/DD/YYYY HH:MM:SS tt in your computer, the generated string would be something like "05/07/2019 06:00:00 AM".
For comparison purpose, I would then convert the string to datetime format by using datetime.datetime.strptime(i,"%m/%d/%Y %I:%M:%S %p"). This works prefectly fine, however if someone else whose system date/time format is different from' MM/DD/YYYY HH:MM:SS tt' runs my script, he would get a mismatch error as the string can no longer be converted by %m/%d/%Y %I:%M:%S %p.
So would it be possible to make the desired datetime format become a variable argument in the strptime function? Or even simpler, just make the format to be the same as the system's date/time format.
You can use try and except to fix this (although there might be another way)
try:
datetime.datetime.strptime(i,"%m/%d/%Y %I:%M:%S %p")
except TypeError:
try:
datetime.datetime.strptime(i,"%d/%m/%Y %I:%M:%S %p")
except:
try:
datetime.datetime.strptime(i,"%d/%m/%y %I:%M:%S %p")
# and so on....

Python format date of the form "Monday, January 1, 1991"

I'm creating a web scraper and I'm running into an issue where the date the website gives me is of the form "Monday, January 1, 1991"
What's the best way to format this into a "MM-DD-YYYY" format? Should I split on the comma, pull out the month and convert it to a number, and then put the numbers together? Or is there some quicker way to do this?
Use the datetime module, using strptime to parse to a datetime object, then strftime to format as you need it:
from datetime import datetime
date = datetime.strptime("Monday, January 1, 1991", "%A, %B %d, %Y")
print(date.strftime("%m-%d-%Y"))
which outputs:
01-01-1991
For the record, any time you're considering rolling your own parser, the answer is almost always "Don't". Rolling your own parser is error-prone; if at all possible, look for an existing parser.

how to convert and subtract dates, times in python

I have the following date/time:
2011-09-27 13:42:16
I need to convert it to:
9/27/2011 13:42:16
I also need to be able to subtract one date from another and get the result in HH:MM:SS format. I have tried to use the dateutil.parser.parse function, and it parses the date fine but sadly it doesn't seem to get the time correctly. I also tried to use another method I found on stackoverflow that uses "time", but I get an error that time is not defined.
You can use datetime's strptime function:
from datetime import datetime
date = '2011-09-27 13:42:16'
result = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
You were lucky, as I had that above line written for a project of mine.
To print it back out, try strftime:
print result.strftime('%m/%d/%Y %H:%M:%S')
Use python-dateutil:
import dateutil.parser as dateparser
mydate = dateparser.parse("2011-09-27 13:42:16",fuzzy=True)
print(mydate.strftime('%m/%d/%Y T%H:%M:%S'))
http://docs.python.org/library/datetime.html#datetime.datetime.strptime
and
http://docs.python.org/library/datetime.html#datetime.datetime.strftime
(And the rest of the datetime module.)

Categories