0

When i convert datetime to timestamp with am/pm and return timestamp back to datetime again it alway return 'am' even the actually datetime that i input is have 'pm'

This is my code.

from datetime import date, datetime

# convert datetime to timestamp
dt_tsp = datetime.timestamp(datetime.strptime('09 June 2020 02:47 PM', '%d %B %Y %H:%M %p'))

# convert timestramp to datetime
tsp_dt = datetime.fromtimestamp(dt_tsp).strftime('%d %B %Y %H:%M %p')

# result
print(tsp_dt)
# 09 June 2020 02:47 AM // alway am

So how can i fix the problem

Kaow
  • 483
  • 2
  • 9
  • 22

2 Answers2

1

Your problem is in your format string, %p needs to be used with %I for parsing hours (see the third note in the documentation):

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

So change your code to use %I instead of %H:

from datetime import date, datetime

dt_tsp = datetime.timestamp(datetime.strptime('09 June 2020 02:47 PM', '%d %B %Y %I:%M %p'))
tsp_dt = datetime.fromtimestamp(dt_tsp).strftime('%d %B %Y %I:%M %p')
print(tsp_dt)

Output:

09 June 2020 02:47 PM
Nick
  • 138,499
  • 22
  • 57
  • 95
0

%H means 24-hour clock. To use 12-hour clock, replace %H with %I. And in the future please read the documentation

Błotosmętek
  • 12,717
  • 19
  • 29