How to Account for Period (Am/Pm) Using Strftime

How can I account for period (AM/PM) using strftime?

The Python time.strftime docs say:

When used with the strptime() function, the %p directive only
affects the output hour field if the %I directive is used to parse
the hour.

Sure enough, changing your %H to %I makes it work.

How can I account for period (a. m. /p. m.) using strftime?

You might want to look into regex for pre-processing your dates before formatting them.

import re

# quick example for how to substitute with regex if you're looking at one string at a time
print(re.sub("p. m.", "PM", '25/9/19 8:59 p. m.'))
print(re.sub("a. m.", "PM", '25/9/19 8:59 a. m.'))

# some type of iterable of these dates with bad am/pm characters
list_of_dates = ['25/9/19 8:59 p. m.', '25/9/19 8:59 a. m.', '25/9/19 8:59 a. m.', '25/9/19 8:59 p. m.']

# you can "pre-compile" your regex patterns so they're faster to work with
pattern_am = re.compile("a. m.")
pattern_pm = re.compile("p. m.")

# then you can use list comprehension to apply the regex pattern substitution to the entire list/series
corrected_dates = [pattern_am.sub("AM", x) for x in list_of_dates]
corrected_dates = [pattern_pm.sub("PM", x) for x in corrected_dates]

Others have correctly pointed out using .replace() string method. You can also wrap that into a list comprehension as well. My assumption here is that you have more than a single date that you need to "fix." If so, I would do some research on list comprehensions. For something quick like this, they tend to make your code more readable than for-loops.

corrected_dates = [x.replace('a. m.', 'AM') for x in list_of_dates] 
corrected_dates = [x.replace('p. m.', 'PM') for x in corrected_dates]

Converting python string to datetime obj with AM/PM

datetime.strptime() is used for converting a string to a datetime object. When using strptime() you have to specify the correct format in which the date/time in the string exists.

In your case the format should be '%Y-%m-%d %H:%M:%S'.

Example:

>>> test = '2015-08-12 13:07:32'
>>> import datetime
>>> datetime.datetime.strptime(test, '%Y-%m-%d %H:%M:%S')
datetime.datetime(2015, 8, 12, 13, 7, 32)

If what you really want is the date-time back as a string with the AM/PM, then you need to use strftime() to convert it back to string with the format you want. In this case the format would be '%Y-%m-%d %I:%M:%S %p'. Example:

>>> datetime.datetime.strptime(test, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %I:%M:%S %p')
'2015-08-12 01:07:32 PM'

datetime objects internally do not store (and do not have to store) the AM/PM information, since that can be easily calculated from the hour.

Determining time with AM and PM

Use f-strings to construct your datetime objects:

current_hour = 12
current_minute = 37
current_section = "AM"
due_hour = 12
due_minute = 0
due_section = "PM"

import datetime as dt
day = dt.date.today()

dateFormat = '%Y-%m-%d %I:%M %p'
current = dt.datetime.strptime(f'{day.year}-{day.month}-{day.day} {current_hour}:{current_minute} {current_section}', dateFormat)
deadline = dt.datetime.strptime(f'{day.year}-{day.month}-{day.day} {due_hour}:{due_minute} {due_section}', dateFormat)

print ("Current: ", current)
print ("Deadline:", deadline)
print(current > deadline)

Output:

Current:  2020-08-27 00:37:00
Deadline: 2020-08-27 12:00:00
False

How can I account for AM/PM in string to DateTime conversion in pyspark?

You can do like below to achieve your result

from pyspark.sql import Row

df = sc.parallelize([Row(visit_dts='5/1/2018 3:48:14 PM')]).toDF()

import pyspark.sql.functions as f

web = df.withColumn("web_datetime", f.from_unixtime(f.unix_timestamp("visit_dts",'MM/dd/yyyy hh:mm:ss aa'),'MM/dd/yyyy HH:mm:ss'))

This should give you

web.show()

+-------------------+-------------------+
| visit_dts| web_datetime|
+-------------------+-------------------+
|5/1/2018 3:48:14 PM|05/01/2018 15:48:14|
+-------------------+-------------------+

Get AM or PM using 'time'

I read the documentation carefully and finally build that piece of code by myself:

time.strftime("%a %b %d %I:%M:%S %p %Y")

How to make pythons datetime object show AM and PM in lowercase?

Try changing '%p' to '%P'. Whether '%P' is supported depends on the 'strftime' function provided by the platform C library.



Related Topics



Leave a reply



Submit