Login

Translate datetime format strings from Python to PHP

Author:
bernd-wechner
Posted:
April 17, 2016
Language:
Python
Version:
1.7
Tags:
datetime date format time
Score:
0 (after 0 ratings)

A simple Python function that converts a Python datetime formatting string to its nearest PHP equivalent.

Python and PHP use different format string conventions when specifying datetime formats:

Working with Django the Date, Time and DateTime widgets all use Python format strings as stored in:

  • django.conf.global_settings.DATE_INPUT_FORMATS
  • django.conf.global_settings.TIME_INPUT_FORMATS
  • django.conf.global_settings.DATETIME_INPUT_FORMATS

but if you want to use a datetime widget like the datetimepicker here:

http://xdsoft.net/jqplugins/datetimepicker/

then you'll find it uses PHP format specifiers.

If you want Django and the datetimepicker to populate a field in the same way, you need to ensure they use the same format.

So I add to the Django from context the default format as follows:

context["default_datetime_input_format"] = datetime_format_python_to_PHP(DATETIME_INPUT_FORMATS[0])

and in the template Javascript on my form for the datetimepicker i give it:

"format": {{default_datetime_input_format}}

and the datetimepicker now populates the the datetime field in the same format as Django.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def datetime_format_python_to_PHP(python_format_string):
    """Given a python datetime format string, attempts to convert it to the nearest PHP datetime format string possible. 
    """
    python2PHP = {"%a": "D", "%a": "D", "%A": "l", "%b": "M", "%B": "F", "%c": "", "%d": "d", "%H": "H", "%I": "h", "%j": "z", "%m": "m", "%M": "i", "%p": "A", "%S": "s", "%U": "", "%w": "w", "%W": "W", "%x": "", "%X": "", "%y": "y", "%Y": "Y", "%Z": "e" }

    php_format_string = python_format_string
    for py, php in python2PHP.items():
        php_format_string = php_format_string.replace(py, php)
    
    return php_format_string

More like this

Comments

Please login first before commenting.