SoFunction
Updated on 2025-03-03

How to convert a standardized date and time format into a non-standardized format

Python standardized date and time format converted to non-standardized format

Scene Example

1. The time of dynamic posts posted by friends in the circle of friends is shown as: XX days ago, XX months ago, just X years ago...

2. The date format shown on the chat message: Just now, X minutes ago...

Requirement description:

1. It is required to convert a time similar to 2024-03-05 18:00:00 combined with the current time into a format like 1 day ago.

2. You only need to know the target time to obtain the conversion results, such as YYYY-MM-DD hh:mm:ss to XXXX

Without further ado, just demonstrate the code:

from datetime import datetime, timedelta


def humanize_datetime(db_datetime_str):
    # parse database date and time string    db_datetime = (db_datetime_str, '%Y-%m-%d %H:%M:%S')

    # Get the current time    now = ()

    # Calculate the time difference    time_diff = now - db_datetime

    # Define the threshold for time units    minute_diff = timedelta(minutes=1)
    hour_diff = timedelta(hours=1)
    day_diff = timedelta(days=1)
    month_diff = timedelta(days=30)  # Assume that an average of 30 days per month    year_diff = timedelta(days=365)  # Assume 365 days a year
    # Calculate the description based on the time difference    if time_diff < minute_diff:
        return "just"
    elif time_diff < 2 * minute_diff:
        return "1 minute ago"
    elif time_diff < hour_diff:
        return f"{time_diff.seconds // 60}min ago"    elif time_diff < 2 * hour_diff:
        return "1Hour ago"
    elif time_diff < day_diff:
        return f"{time_diff.seconds // 3600} hours ago"    elif time_diff < 2 * day_diff:
        return "yesterday"
    elif time_diff < month_diff:
        return f"{time_diff.days // 7} weeks ago"    elif time_diff < 2 * month_diff:
        return "1Months ago"
    elif time_diff < year_diff:
        return f"{time_diff.days // 30}months ago"    elif time_diff < 2 * year_diff:
        return "Half a year ago"
    else:
        return db_datetime.strftime('%Y-%m-%d %H:%M:%S')


# Example usage# db_datetime = "2024-03-04 16:30:00"
# print(humanize_datetime(db_datetime))

Code description:

1. The packages introduced in the above code are built into python

2. The time format of this function is:YYYY-MM-DD hh:mm:ss

3. The expression forms of many cases can be derived based on the time difference calculation, the above is just as an example.

4. The code will be used at the end. It will be OK to copy all the copies to the project once!

Python time standardization problem

Date formatting is a very common operation in Python. There are many ways to process dates and times. Converting date formats is a common function.

1. Basic methods to obtain time

  • 1.1 ()

time time() function returns the timestamp of the current time (the number of floating point seconds elapsed after the 1970th century). Generally speaking, timestamps represent offsets calculated in seconds starting at 00:00:00 on January 1, 1970.

import time
timeStamp = ()
# print(current_time) 
# Output: 1614846609.368156
  • 1.2 ()

The time localtime() function is similar to gmtime(), and it is used to format the time stamp to the local time and return it in the form of the time ancestor (struct_time).

import time
struct_time = ()
# print(struct_time) 
# Output: time.struct_time(tm_year=2021, tm_mon=3, tm_mday=4, tm_hour=16, tm_min=30, tm_sec=10, tm_wday=3, tm_yday=63, tm_isdst=0)
  • 1.3 ()
import datetime
data_time = ()
# print(data_time)
# Output: 2021-03-04 16:30:10.000000

2. Format time (based on time ancestor)

Next, we format the time in the form of time ancestor obtained by struct_time = ().

  • 2.1 ()
format_time_1 = (struct_time)
# print(format_time_1)
# Output: Thu Mar  4 16:30:10 2021
  • 2.2 ()
format_time_2 = ("%Y-%m-%d %H:%M:%S", struct_time) 
# print(format_time_2)
# Output: 2021-03-04 16:30:10

Time and date formatting symbols in python:

%y Double-digit year representation(00-99)
%Y Four-digit year representation(000-9999)
%m month(01-12)
%d One day of the month(0-31)
%H 24Hour system hours(0-23)
%I 12Hour system hours(01-12)
%M Minutes(00=59)
%S Second(00-59)

3. Common operations of time

  • 3.1 Convert string time to time stamp
t = "2021-03-04 16:30:10"
#Convert it to a time arraytimeStruct = (t, "%Y-%m-%d %H:%M:%S" )
#Convert to timestamp:timeStamp = int ((timeStruct))
# print (timeStamp)
# Output: 1614846610
  • 3.2 Convert timestamps to specified format dates
timeStamp = 1614846610
localTime = (timeStamp)
strTime = ( "%Y-%m-%d %H:%M:%S" , localTime)
print (strTime)
# Output: 2021-03-04 16:30:10
  • 3.3 Get the time three days ago
import time
import datetime
#Get the date in the time array format firstthreeDayAgo = (() - (days=3))
#Convert to timestamp:timeStamp = int((()))
#Convert to other string formats:strTime = ( "%Y-%m-%d %H:%M:%S" )
# print (strTime)
# Output: 2021-03-01 16:30:10

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.